用途
本技能用于对 UI 组件进行隔离测试,基于 Playwright 的实验性组件测试(Component Testing)功能实现。它支持 React、Vue、Svelte 以及 Solid,适合在单独挂载的组件上验证渲染结果、交互行为与视觉状态,而不必启动完整应用。
主要能力
- 通过
mount挂载单个组件,并传入 props、事件处理函数、子元素/插槽等。 - 断言组件渲染内容与状态,例如文本可见性、CSS 类名、角色查询结果。
- 模拟用户交互,例如点击按钮、填写表单、悬停与聚焦。
- 支持与常见状态管理/上下文集成,示例中包含 React 的 Context Provider、Vue 的 Pinia 测试插件。
- 支持视觉回归截图对比(
toHaveScreenshot)、可访问性检测(@axe-core/playwright)、响应式视口切换、加载态与错误态验证。 - 支持测试 Hook 与 fixture 扩展,例如自动 mock API、自定义带 Provider 的 mount。
- 提供 React、Vue、Svelte 的安装包与配置示例。
使用方式
安装(以 React 为例):
npm init playwright@latest -- --ct
# Select React when prompted
或手动安装:
npm install -D @playwright/experimental-ct-react
Vue:
npm install -D @playwright/experimental-ct-vue
Svelte:
npm install -D @playwright/experimental-ct-svelte
配置示例(playwright-ct.config.ts):
import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
testDir: './src',
testMatch: '**/*.spec.tsx',
use: {
ctPort: 3100,
ctViteConfig: {
// Custom Vite config for component tests
},
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
});
运行测试:
# Run all component tests
npx playwright test -c playwright-ct.config.ts
# Run specific test file
npx playwright test Button.spec.tsx -c playwright-ct.config.ts
# Run with UI mode
npx playwright test -c playwright-ct.config.ts --ui
# Update snapshots
npx playwright test -c playwright-ct.config.ts --update-snapshots
适用场景
- 在隔离环境中测试组件交互与渲染逻辑。
- 验证组件的多种状态:默认、加载、错误、空、成功。
- 进行组件级视觉回归与可访问性检查。
- 验证组件在不同视口下的响应式行为。
- 在 mock 外部 API 依赖的前提下测试组件。
- 作为 E2E 测试的补充:组件测试关注逻辑与局部行为,E2E 关注集成流程。
限制
- 基于 Playwright 的实验性组件测试功能,资料中标注为 experimental。
- 具体收费、价格、平台支持范围等事实资料暂未提供。