Playwright テスト実行
この章では、Playwright テストの実行方法、コマンドライン引数、およびさまざまなフィルタリングテクニックを総合的に紹介します。
基本的な実行コマンド
例
# すべてのテストを実行
npx playwright test
# デフォルトでは package.json に設定されたプロジェクトを使用
npm test
npx playwright test
# デフォルトでは package.json に設定されたプロジェクトを使用
npm test
特定のテストをフィルタリング
ファイルパスで
# 运行单个测试文件 npx playwright test tests/login.spec.ts # 运行目录中的所有测试 npx playwright test tests/user/ # 运行多个文件(空格分隔) npx playwright test tests/login.spec.ts tests/register.spec.ts
ファイル名のキーワードで
# 运行文件名中包含 "login" 或 "user" 的所有测试 npx playwright test login user
テスト名でフィルタリング(-g / --grep)
# 运行测试名称中包含 "登录" 的测试 npx playwright test -g "登录" # 通过正则表达式筛选 npx playwright test -g "登录|注册"
タグでフィルタリング
例
// テスト内でタグを定義
test('高速スモークテスト @smoke', async ({ page }) => {
// ...
});
test('低速テスト @slow', async ({ page }) => {
// ...
});
test('高速スモークテスト @smoke', async ({ page }) => {
// ...
});
test('低速テスト @slow', async ({ page }) => {
// ...
});
# 只运行带 @smoke 标签的测试 npx playwright test --grep "@smoke" # 跳过带 @slow 标签的测试 npx playwright test --grep-invert "@slow"
ブラウザ制御
ブラウザの指定(--project)
# 只在 Chromium 上运行 npx playwright test --project=chromium # 在多个浏览器上运行 npx playwright test --project=chromium --project=firefox
ヘッド付きモード(--headed)
# 显示浏览器窗口(默认无头) npx playwright test --headed
ブラウザ実行ファイルのパスを指定
# 使用本地安装的 Chrome 而非 Playwright 的 Chromium npx playwright test --project=chromium \ --channel=chrome
実行モード
UIモード(--ui)
# 在 UI 模式下运行(推荐开发和调试时使用) npx playwright test --ui
デバッグモード(--debug)
# 单步调试测试 npx playwright test --debug
並列と繰り返し
並列数の制御(--workers)
# 使用 4 个 worker 并行运行 npx playwright test --workers=4 # 单线程运行(方便调试) npx playwright test --workers=1
繰り返し実行(--repeat-each)
# 每个测试重复运行 3 次(检查稳定性) npx playwright test --repeat-each=3
シャード実行(--shard)
# 在 CI 上分片运行(分 4 片,当前为第 1 片) npx playwright test --shard=1/4 # 第 2 片 npx playwright test --shard=2/4
シャードは CI で複数のマシンがテストを並列実行する際によく使用され、各マシンは一部のみを実行し、最終的に結果を統合します。
スクリーンショットとトレース制御
# 更新视觉回归的基准截图 npx playwright test --update-snapshots # 强制生成 Trace 文件(即使配置中没有开启) npx playwright test --trace on # 查看最后一次运行的 Trace npx playwright show-trace test-results/.../trace.zip
よく使うコマンド早見表
| コマンド | 説明 |
|---|---|
npx playwright test | すべてのテストを実行 |
npx playwright test file.spec.ts | 指定ファイルを実行 |
npx playwright test -g "关键词" | テスト名でフィルタリング |
npx playwright test --project=chromium | ブラウザを指定 |
npx playwright test --headed | ヘッド付きモード(ブラウザウィンドウを表示) |
npx playwright test --ui | UIモード |
npx playwright test --debug | デバッグモード |
npx playwright test --workers=4 | worker 数を指定 |
npx playwright test --shard=1/4 | シャード実行 |
npx playwright test --repeat-each=3 | 繰り返し実行 |
npx playwright test --update-snapshots | ビジュアルベースラインのスクリーンショットを更新 |
npx playwright show-report | HTMLレポートを表示 |
npx playwright show-trace trace.zip | トレースを表示 |
npx playwright codegen url | コード生成器を起動 |