How to understand a Jest or Vitest test suite codebase
Tests are executable documentation. A good suite shows how each module is meant to be called and what it should return, including edge cases the code alone doesn't make obvious. Knowing how mocks and setup files work keeps you from being misled by them.
How to tell it's Jest or Vitest test suite
jest.config.*orvitest.config.*, or atestblock invite.config.ts- Files named
*.test.ts,*.spec.tsor folders called__tests__ jest.mockorvi.mockcalls and a__mocks__folder
Where things usually live
- jest.config.ts / vitest.config.ts
- Test environment, setup files, path aliases, coverage.
- test/setup.ts
- Global setup: matchers, fake timers, mocked globals.
- **/__tests__/ or *.test.ts
- The tests, colocated or in a separate folder.
- __mocks__/
- Manual mocks that replace modules in tests.
- test/fixtures/
- Sample data and files.
Conventions, not rules. Real projects rename and move things, so confirm against the repository.
Where to start reading
- The config and setup files, to know what every test inherits
- The tests for the module you're learning
- Mocks, to know which real code a test is not exercising
How a request moves through the code
- The runner loads the config and runs setup files.
vi.mockandjest.mockcalls are hoisted above imports, replacing modules before the test file loads them.- Each
describeanditblock arranges inputs, calls the code, and asserts on the result. - Hooks such as
beforeEachreset state between tests.
Questions to ask about the repository
- What behaviour do the tests for this module describe?
- Which modules are mocked, and does that hide real integration paths?
- Which important functions have no tests?
What trips people up
- Mock calls are hoisted, so a mock written at the bottom of a file still applies to imports at the top.
- A global mock in a setup file can make every test pass against fake behaviour.