This project uses Vitest for testing React components and other code. This document provides an overview of the testing setup and guidelines.
The testing environment is configured with:
- Vitest: Fast testing framework powered by Vite
- @testing-library/react: For rendering and testing React components
- @testing-library/jest-dom: For additional DOM matchers
- happy-dom: For simulating a DOM environment
# Run all tests
bun run test
# Run tests in watch mode
bun run test:watch
# Run specific tests by name pattern
bun run test --run ComponentName
# Run tests with coverage
bun run test:coverage
Test files should be placed in a __tests__
directory adjacent to the component or in the same directory with a .test.tsx
or .test.jsx
extension.
Example:
src/
components/
Button.tsx
__tests__/
Button.test.tsx
For React components, we use React Testing Library to render and interact with components. Here's a basic example:
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MyComponent } from '../MyComponent'
describe('MyComponent', () => {
it('renders correctly', () => {
render(<MyComponent />)
expect(screen.getByText('Expected Text')).toBeInTheDocument()
})
})
Use Vitest's mocking capabilities to mock dependencies:
import { vi } from 'vitest'
// Mock a module
vi.mock('module-name', () => ({
functionName: vi.fn(),
}))
// Mock a specific function
const mockFn = vi.fn()
For testing asynchronous code:
it('handles async operations', async () => {
render(<AsyncComponent />)
// Wait for element to appear
await screen.findByText('Loaded')
// Make assertions
expect(screen.getByText('Loaded')).toBeInTheDocument()
})
- Test Behavior, Not Implementation: Focus on what the component does, not how it does it.
- Keep Tests Independent: Each test should be able to run independently of others.
- Use Descriptive Test Names: Test names should clearly describe what is being tested.
- Avoid Testing Implementation Details: Test the public API of your components, not internal details.
- Clean Up After Tests: Use
afterEach
orafterAll
to clean up any side effects.
We aim for high test coverage, but quality of tests is more important than quantity. Run coverage reports to identify areas that need more testing:
bun run test:coverage
Coverage reports are generated in the coverage
directory.