Playwright基礎篇(九):強化報告系統
 自定義測試步驟
- 
定義清晰的測試階段
- 前置準備、執行動作和驗證結果的明確區分
 - 使用 
test.step()功能組織測試階段 
test('搜尋功能測試', async ({ page }) => { await test.step('前置準備:打開網站首頁', async () => { await page.goto('https://example.com'); }); await test.step('執行測試:輸入關鍵字並搜尋', async () => { await page.fill('#search-box', '自動化測試'); await page.click('#search-button'); }); await test.step('驗證結果:檢查搜尋結果', async () => { await expect(page.locator('.search-results')).toBeVisible(); await expect(page.locator('.result-count')).toContainText('結果'); }); }); - 
步驟命名最佳實踐
- 採用「動詞+名詞」結構(例如:「驗證登入」、「檢查購物車」)
 - 保持一致的命名模式
 - 避免過於簡略或冗長的描述
 - 包含相關功能或元素名稱
 
 
截圖功能運用
- 自動截圖設置
- 在配置檔中啟用自動截圖
 
// playwright.config.js module.exports = { use: { screenshot: 'on', // 'on' | 'off' | 'only-on-failure' 
失敗時截圖*
- 僅在測試失敗時捕捉畫面
 
// playwright.config.js
module.exports = {
  use: {
    screenshot: 'only-on-failure',
  },
};
- 自定義截圖時機
- 在測試中的特定時間點手動截圖
 
test('結帳流程', async ({ page }) => { await page.goto('https://example.com/checkout'); // 填寫結帳表單 await page.fill('#name', '測試用戶'); await page.fill('#email', 'test@example.com'); // 在提交前截圖 await page.screenshot({ path: 'checkout-form-filled.png' }); await page.click('#submit-button'); // 成功頁面截圖 await page.screenshot({ path: 'checkout-success.png' }); }); 
影片錄製
* **設置測試錄影** * 在配置檔中啟用錄影功能
// playwright.config.js
module.exports = {
  use: {
    video: 'on-first-retry',  // 'on' | 'off' | 'on-first-retry' | 'retain-on-failure'
  },
};
- 影片檔案管理
- 控制錄製的影片儲存和保留策略
 
// playwright.config.js module.exports = { use: { video: 'retain-on-failure', // 只保留失敗的測試影片 }, outputDir: './test-results/', // 指定影片輸出目錄 }; 
整合報告工具
- 
HTML 報告生成
- 設置 Playwright 的 HTML 報告
 
// playwright.config.js module.exports = { reporter: [ ['html', { outputFolder: './playwright-report/' }], ['json', { outputFile: './test-results/test-results.json' }] ], };- 執行測試並生成報告
 
npx playwright test --reporter=html - 
視覺化報告解析
- 測試結果概覽(通過/失敗/跳過)
 - 測試執行時間分析
 - 失敗測試的詳細資訊和截圖
 - 測試步驟的詳細記錄
 - 影片回放功能(如果啟用)
 
 
通過這些配置管理策略,即使是小團隊也能建立可靠的自動化測試系統,減少手動測試負擔,提高產品質量。
分享這篇文章: