-
Notifications
You must be signed in to change notification settings - Fork 4
Vitest
Vitest is a test framework, powered by Vite. It is a modern alternative to Jest, Chai, ...
For our project, it offers
- Performance: Uses Vite's dev server logic to run fast
-
Compatibility: It shares a common configuration with Vite (
vite.config.ts), reducing setup complexity for projects already using Vite (like our React frontend).
TDD (Test Driven Development): It is a methodology where we write the test before the code.
- ๐ด Write a failing test.
- ๐ข Write the minimal code to pass the test.
- ๐ข Refactor the code while keeping the test green.
AAA Pattern: It is the standard structure for a unit test.
- Arrange: Set up the necessary objects, variables, and mocks.
- Act: Execute the function or component under test.
- Assert: Verify the result matches the expectation.
Choosing Test Cases: Focus on:
- Happy Path: Does it work with standard input?
- Edge Cases: What happens with empty containers, null values, or extreme numbers?
- Error Handling: Does it throw/catch errors correctly?
npm install -D vitest @vitest/coverage-v8Note
We can try to have a single installation at project root for common cases. Yet some modules require additional dependencies
-
environment:jsdomfor frontend, otherwisenode -
coveragerequires a specific config for CI job
Basic commands : vitest --run and vitest run --coverage
Example
// Groups tests suite (ex : tests for an API path)
describe('GET /resource/:id', () => {// Single test (can also use `test`) name should be descriptive
it('should return 500 in case of server error', () => {// assertions with `expect`
expect(response.statusCode).toBe(200);Warning
Till returned values are not defined in a stable way, assertions should focus on the basics (http status) Later on we could enrich tests with assertions on returned content, called functions, etc
When doing unit test we should mock external dependencies (ex : functions from other layers, returns from DB)
Example
// mocking the service
vi.mock('../src/services/users-service.js', () => ({
findUser: vi.fn(),
}));// specific return value for this test
vi.mocked(service.findUser).mockResolvedValue({ id: 1, name: 'Alice' });Note
Tests should not reuse resources from codebase and should have their own mocks. They can be shared among tests though (ie. mock factories in their own files, possibly using libs such as Faker)
- use Fastify
.inject() - pass required headers
- Requires
@testing-library/reactprovidingrender,screen,fireEvent - make assertions with
toHaveTextContent(), ...
Filtering test matching a filename npx vitest friends.controllers
vitest run --coverage
-
Requires
@vitest/ui -
see console.log outputs in real time
| โ Do | โ Don't |
|---|---|
Isolate tests: Each test should run independently. Reset mocks in beforeEach. |
Couple tests: Don't rely on the state left by a previous test (e.g., DB records). |
| Test behavior: Focus on what the component does, not how it's implemented. | Test implementation details: Avoid testing private methods or specific CSS class names unless necessary. |
Use descriptive names: it('should return 400 if email is missing')
|
Use vague names: it('should work'). |
| Mock external I/O: Mock databases and fetch requests to keep tests fast and deterministic. | Make real API calls: Never hit real production APIs in unit tests. |
Use describe blocks: Group related tests for better readability in reports. |
Write flat files: Don't put all tests in the root of the file without structure. |
| Type | Resource | Notes |
|---|---|---|
| ๐ | Vitest Official Docs | Main reference |
| ๐ | React Testing Library | Standard for React component testing |
| ๐ | Fastify Testing | Guide on .inject() and mocking |
- Gateway Service - API Gateway & JWT validation
- Auth Service - Authentication & 2FA/TOTP
- AI Service - AI opponent
- API Documentation - OpenAPI/Swagger
- DB Schema - Databases
- Fastify - Web framework
- Prisma - ORM
- WebSockets - Real-time communication
- Restful API - API standards
- React - UI library
- CSS - Styling
- Tailwind - CSS framework
- Accessibility - WCAG compliance
- TypeScript - Language
- Zod - Schema validation
- Nginx - Reverse proxy
- Logging and Error management - Observability
- OAuth 2.0 - Authentication flows
- Two-factor authentication - 2FA/TOTP
- Avalanche - Blockchain network
- Hardhat - Development framework
- Solidity - Smart contracts language
- Open Zeppelin - Security standards
- ESLint - Linting
- Vitest - Testing
- GitHub Actions - CI/CD
- Husky, Commit lints and git hooks - Git hooks
- ELK - Logging stack
๐ Page model