How to read tests as documentation for a codebase
Tests show how code is meant to be called, what it returns and which edge cases matter. How to find the right tests, read them and avoid being misled by mocks.
When documentation is missing or out of date, tests are often the most accurate description of a codebase. Unlike docs, they run, so if they pass they're true. Learning to read tests well is one of the fastest ways into unfamiliar code.
What tests tell you that code doesn't
- Intended usage. How a function is meant to be called, with realistic arguments.
- Expected results. What it should return, written as an assertion.
- Edge cases. The empty list, the expired token, the duplicate request. Authors write tests for the cases they've worried about.
- History. A test named after a bug ("does not double-charge on retry") records an incident.
Find the right tests
- Look for files next to the code (
pricing.test.tsbesidepricing.ts) or in mirrored folders undertest/or__tests__/. - Search test files for the function name.
- Run the suite with a filter (
vitest pricingorjest -t "totals") and read the output names.
Read in the right order
- The
describeanditnames. Read them like a table of contents. Good test names form a specification. - Setup.
beforeEachblocks, fixtures and factories show the starting state. - One test end to end. Arrange, act, assert.
- The edge-case tests. These are often the most informative.
Watch out for mocks
Mocks replace real modules, which makes tests fast but can make them misleading.
- Find what's mocked. Look for
vi.mock,jest.mockand__mocks__folders. Mock calls are hoisted to the top of the file, so a mock written at the bottom still applies. - Check global setup. A setup file can mock modules for every test.
- Mocked tests describe contracts, not integration. A test that mocks the database tells you what a service expects from it, not that the real query works.
Different kinds of tests tell different stories
| Test type | What it documents |
|---|---|
| Unit tests | How individual functions behave |
| Integration tests | How modules work together, often with a real database |
| End-to-end tests | What users can do, step by step |
| Snapshot tests | What output looks like, but rarely why |
End-to-end tests (Playwright, Cypress) are especially good for learning a product's main flows. See our Playwright guide.
Missing tests are information too
An important module with no tests is a risk. A test file with skipped tests (it.skip) or TODO comments points at known problems.
Write a test to confirm understanding
When you think you understand a function, write a small test that asserts what you believe it does. If it fails, you've learned something.
With AI
Ask RepoGrasp "what behaviour do the tests for calculateTotals describe, and which cases aren't covered?" It reads test files as well as source, and cites both. Then open the tests and run them yourself.