Skip to Content

Playwright

playwright  中集成覆盖率收集与报告生成

使用该方案的优势

对于端到端测试而言,该方案的核心优势包括:

  • 支持现代化 Web 应用:现代化的 Web 应用都会经过 JS bundle 打包,Playwright 提供的默认方案只能对原生 JS 等简单场景使用 V8 收集覆盖率,而该方案通过 Babel 插桩可以准确收集打包后代码的覆盖率
  • 确保变更代码覆盖率完整性@canyonjs/babel-plugin 会在构建时生成一份初始覆盖率数据,确保在 CI 集成时,能够收集到因懒加载而可能丢失的变更代码覆盖率
  • 与 Playwright 无缝集成:通过扩展 Playwright 的 context fixture,在用户代码层面完全实现,不会修补或替换 Playwright 的测试运行器
  • 灵活的覆盖率报告:支持本地生成 HTML 报告,也可以上传到 Canyon 服务器进行统一管理和分析
Tip

该方案特别适合使用现代构建工具(如 Vite、Webpack)的 React、Vue 等框架项目,能够准确追踪打包后代码的覆盖率情况。

以新项目的形式开始

创建 React 项目

使用 Vite  创建一个 React 项目:

npm create vite@latest my-react-app -- --template react-ts

安装代码插桩所需的 Babel 插件:

npm install babel-plugin-istanbul @canyonjs/babel-plugin -D

初始化 Playwright

在项目根目录下初始化 Playwright:

npm init playwright@latest

按照提示选择配置选项。

编写 Playwright 测试用例

创建一个测试文件来测试你的 React 应用:

tests/example.spec.ts
import { test, expect } from './baseTest'; test('首页加载测试', async ({ page }) => { await page.goto('http://localhost:5173'); await expect(page).toHaveTitle(/React/); });

安装 @canyonjs/playwright 并创建 baseTest.ts

安装 @canyonjs/playwright 包:

npm install @canyonjs/playwright -D

创建 baseTest.ts 文件,继承 Playwright 的 test 以支持覆盖率收集:

tests/baseTest.ts
import {test as baseTest} from '@playwright/test'; import {createCoverageContextFixture} from '@canyonjs/playwright' export const test = baseTest.extend({ context: createCoverageContextFixture({ outputDir:'.canyon_output' }) }); export const expect = test.expect;

配置 Playwright 在运行时启动开发服务器

编辑 playwright.config.ts,添加 webServer 配置,让 Playwright 在运行测试前自动启动开发服务器:

playwright.config.ts
import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ // 测试目录 testDir: './tests', // 在运行测试前启动开发服务器 webServer: { command: 'npm run dev', url: 'http://localhost:5173', reuseExistingServer: !process.env.CI, timeout: 120 * 1000, }, // 使用项目中的浏览器 projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] }, }, ], });

现在运行测试时,Playwright 会自动启动 npm run dev,等待服务器就绪后再执行测试用例。

配置测试脚本生成覆盖率报告

安装生成覆盖率报告所需的依赖:

npm install nyc @canyonjs/report-html -D

package.json 中添加测试和生成覆盖率报告的脚本:

package.json
{ "scripts": { "dev": "vite", "gen-coverage-report": "nyc report --reporter=@canyonjs/report-html --temp-dir=./.canyon_output", "test": "playwright test && npm run gen-coverage-report" } }

现在运行 npm test 时,会在测试用例执行完成后自动生成覆盖率报告。覆盖率数据会从 .canyon_output 目录中读取,并生成 HTML 格式的覆盖率报告。