TESTING
Guidelines for UNIT TESTING
VITEST
- •
Leverage the
viobject for test doubles - Usevi.fn()for function mocks,vi.spyOn()to monitor existing functions, andvi.stubGlobal()for global mocks. Prefer spies over mocks when you only need to verify interactions without changing behavior. - •
Master
vi.mock()factory patterns - Place mock factory functions at the top level of your test file, return typed mock implementations, and usemockImplementation()ormockReturnValue()for dynamic control during tests. Remember the factory runs before imports are processed. - •
Create setup files for reusable configuration - Define global mocks, custom matchers, and environment setup in dedicated files referenced in your
vitest.config.ts. This keeps your test files clean while ensuring consistent test environments. - •
Use inline snapshots for readable assertions - Replace complex equality checks with
expect(value).toMatchInlineSnapshot()to capture expected output directly in your test file, making changes more visible in code reviews. - •
Monitor coverage with purpose - Configure coverage thresholds in
vitest.config.tsto ensure critical code paths are tested, but focus on meaningful tests rather than arbitrary coverage percentages. - •
Make watch mode part of your workflow - Run
vitest --watchduring development for instant feedback as you modify code, filtering tests with-tto focus on specific areas under development. - •
Explore UI mode for complex test suites - Use
vitest --uito visually navigate large test suites, inspect test results, and debug failures more efficiently during development. - •
Handle optional dependencies with smart mocking - Use conditional mocking to test code with optional dependencies by implementing
vi.mock()with the factory pattern for modules that might not be available in all environments. - •
Configure jsdom for DOM testing - Set
environment: 'jsdom'in your configuration for frontend component tests and combine with testing-library utilities for realistic user interaction simulation. - •
Structure tests for maintainability - Group related tests with descriptive
describeblocks, use explicit assertion messages, and follow the Arrange-Act-Assert pattern to make tests self-documenting. - •
Leverage TypeScript type checking in tests - Enable strict typing in your tests to catch type errors early, use
expectTypeOf()for type-level assertions, and ensure mocks preserve the original type signatures. - •
Follow 'Arrange', 'Act', 'Assert' approach to test structure for simplicity and readability.