Skip to Content
开发🧪 分层测试单元测试
🧪

单元测试最佳实践:

  • 测试用例命名清晰(测试对象_场景_预期)
  • 每个测试只验证一个逻辑单元
  • 使用 describe/it 分层组织用例
  • 避免测试实现细节

核心概念

单元测试是对软件中最小可测试单元(函数/组件)进行验证的测试方法,具备以下特性:

  • 快速反馈:执行时间应控制在毫秒级
  • 隔离性:用例之间互不影响
  • 确定性:相同输入永远得到相同输出
  • 覆盖全面:包含正常/异常/边界场景

常用工具

框架对比

特性JestVitest
执行环境NodeVite
热更新支持原生支持
TypeScript 支持需要配置开箱即用
执行速度较慢快 50%+
兼容性React 官方推荐Vite 项目首选

配置示例

import { defineConfig } from 'vitest/config'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], test: { globals: true, environment: 'jsdom', coverage: { reporter: ['text', 'json', 'html'], lines: 80, functions: 80 }, setupFiles: './test/setup.js' } });

React 组件测试

import { render, screen } from '@testing-library/react'; import Button from './Button'; import { vi } from 'vitest'; describe('Button组件', () => { it('应正确显示文本内容', () => { render(<Button>点击</Button>); expect(screen.getByRole('button')).toHaveTextContent('点击'); }); it('应触发点击回调', () => { const handleClick = vi.fn(); render(<Button onClick={handleClick} />); screen.getByRole('button').click(); expect(handleClick).toHaveBeenCalledTimes(1); }); it('禁用状态样式', () => { render(<Button disabled />); expect(screen.getByRole('button')).toHaveClass('opacity-50'); }); });

执行命令

# 安装依赖 pnpm add -D vitest @testing-library/react # 运行测试 pnpm test:unit ## CI/CD 集成 ```yaml .github/workflows/ci.yml - name: Run Unit Tests run: npm run test:unit - name: Upload Coverage uses: codecov/codecov-action@v3 with: files: ./coverage/codecov.json
Last updated on