Testing Guide
测试规范,涵盖 Vitest、Testing Library 和测试组织。
Quick Start
typescript
import { describe, it, expect } from 'vitest';
describe('ModuleName', () => {
it('should behavior description', () => {
expect(actual).toBe(expected);
});
});
Test Location
All tests in __tests__/ directory, mirroring source structure:
code
__tests__/ ├── lib/utils/ ├── lib/services/ ├── components/ └── hooks/
File Naming
- •Unit tests:
*.test.ts/*.test.tsx - •Integration tests:
*.spec.ts/*.spec.tsx
Commands
bash
pnpm test # Run all tests pnpm test:watch # Watch mode pnpm test:coverage # Coverage report
Component Test
typescript
import { render, screen } from '@testing-library/react';
import { Button } from '@/components/ui/button';
describe('Button', () => {
it('should render children', () => {
render(<Button>Click</Button>);
expect(screen.getByText('Click')).toBeInTheDocument();
});
});
Mocking
typescript
import { vi } from 'vitest';
vi.mock('@/lib/services', () => ({
UserService: {
getUser: vi.fn().mockResolvedValue({ id: '1' }),
},
}));
Coverage Requirements
- •Normal path - Expected behavior
- •Edge cases - Empty, null, boundary values
- •Error handling - Exception scenarios