跳轉到

3.1 測試組織:describe 與測試檔#

測試檔的慣例#

一個功能區域一個檔案,檔名以 .spec.ts 結尾:

tests/
├── auth.spec.ts       # 登入、註冊、登出
├── cart.spec.ts       # 購物車
├── checkout.spec.ts   # 結帳流程
└── home.spec.ts       # 首頁

describe:分組測試#

用 describe 把相關的測試組織起來:

import { test, expect } from "@playwright/test";

test.describe("登入功能", () => {
  test("正確的帳號密碼應該登入成功", async ({ page }) => {
    // ...
  });

  test("錯誤的密碼應該顯示錯誤訊息", async ({ page }) => {
    // ...
  });

  test("空白表單不應該送出", async ({ page }) => {
    // ...
  });
});

test.describe("購物車", () => {
  test("加入商品後數量應該更新", async ({ page }) => {
    // ...
  });
});

針對分組執行#

npx playwright test -g "登入功能"     # 只跑某個 describe 分組
npx playwright test tests/auth.spec.ts   # 只跑某個檔案

只跑一個測試:test.only#

開發某個測試時,暫時只跑它:

test.only("正在開發的測試", async ({ page }) => {
  // ...
});

⚠️ 警告:commit 前要把 .only 移除,否則 CI 只會跑一個測試,其他的全部被跳過。

跳過與標記#

test.skip("暫時跳過的測試", async ({ page }) => {
  // 不會執行
});

test("只有桌面版要跑", async ({ page, browserName }) => {
  test.skip(browserName === "webkit", "Safari 不測");
  // ...
});

命名習慣#

測試名稱用使用者行為描述,一看就知道在驗證什麼:

// 好:描述使用者行為與預期結果
test("使用者輸入正確密碼後應該進入儀表板", ...);
test("購物車空的時候結帳按鈕應該停用", ...);

// 不好:只描述實作
test("測試 login API", ...);
test("驗證 button disabled", ...);

一個測試一個流程。一個 test 裡驗證十件事,失敗時你不知道是哪件事壞了。