前端测试策略:从单元测试到 E2E

Q

质量工程师

1个月前

前端测试策略:从单元测试到 E2E

测试VitestPlaywright

前端测试策略完全指南

构建可靠的测试体系。

1. 测试金字塔

text
/\

/E2E\ 少量 /------\ /集成测试\ 适量 /----------\ / 单元测试 \ 大量 /--------------\

2. Vitest 单元测试

typescript
import { describe, it, expect } from 'vitest'

describe('utils', () => { it('should format date correctly', () => { expect(formatDate(new Date('2025-01-01'))) .toBe('2025年1月1日') }) })

3. Testing Library 组件测试

typescript
import { render, screen, fireEvent } from '@testing-library/react'

test('counter increments', async () => { render()

await fireEvent.click(screen.getByRole('button'))

expect(screen.getByText('Count: 1')).toBeInTheDocument() })

4. Playwright E2E 测试

typescript
test('user can login', async ({ page }) => {

await page.goto('/login') await page.fill('[name="email"]', 'test@example.com') await page.fill('[name="password"]', 'password') await page.click('button[type="submit"]')

await expect(page).toHaveURL('/dashboard') })

5. 覆盖率目标

  • 单元测试: 80%+
  • 关键路径: 100%
  • E2E: 核心流程
  • 3.2k 阅读