vitest

Vitest

Vitest testing patterns for TypeScript: type-safe mocks, ESM-native, compatible with Vite projects

TypeScript
Testing
Used by 1079 projects

Details

Language / Topic
typescriptTypeScript
Category
Testing

Rules

balanced
- For TypeScript: Only write Vitest tests when resolving a specific user issue or upon explicit request.
- Import core functions as `import { describe, it, expect } from 'vitest';`.
- Use jsdom environment for DOM-related tests and node for others.
- Write focused, isolated test cases.
- Configure Vitest coverage with exclusion patterns and multiple report formats.
- For TypeScript: Import from `vitest`: `import { describe, it, expect, vi, beforeEach } from 'vitest'` — do not mix with Jest globals.
- Mock modules with `vi.mock('../db', () => ({ query: vi.fn<[string], Promise<Row[]>>() }))` — use generic type parameters on `vi.fn<TArgs, TReturn>()` for type-safe mock functions.
- Use `vi.spyOn(obj, 'method').mockResolvedValue(result)` to patch individual methods with typed return values.
- Assert async results: `await expect(fetchUser('1')).resolves.toMatchObject({ id: '1', name: expect.any(String) })` and `await expect(fetchUser('')).rejects.toThrow('invalid id')`.
- Use `vi.useFakeTimers()` with `vi.advanceTimersByTime(ms)` to test debounced functions and polling intervals without real delays.
- Configure per-file environment: `// @vitest-environment jsdom` for DOM tests, `// @vitest-environment node` for server-side code.