Sub topic 16
Writing Isolated, Deterministic, Readable Tests
This chapter assumes you have worked through the earlier chapters. You should already know how to use describe/it, lifecycle hooks, vi.fn, vi.spyOn, vi.mock, and fake timers. Here those tools are put together into a few habits that keep a suite trustworthy as it grows.
A good unit test has three properties:
- Isolated: it passes or fails on its own, whatever order the tests run in and whatever other tests do.
- Deterministic: it gives the same result on every run, on every machine.
- Readable: a failure tells you what broke without making you read the implementation.
Isolation: no shared mutable state
The most common isolation bug is a single object created at the top of a file that every test changes. The first test leaves items behind and the second test sees them. Build fresh state in beforeEach instead, and undo global changes in afterEach.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
function createCart() {
const items = []
return {
add(item) {
items.push(item)
},
total() {
return items.reduce((sum, item) => sum + item.price, 0)
},
}
}
function isExpired(expiresAt) {
return Date.now() > expiresAt
}
describe('cart', () => {
let cart
beforeEach(() => {
cart = createCart()
})
it('starts with a total of 0', () => {
expect(cart.total()).toBe(0)
})
it('sums the prices of added items', () => {
// Arrange
cart.add({ price: 3 })
cart.add({ price: 4 })
// Act
const total = cart.total()
// Assert
expect(total).toBe(7)
})
})
describe('isExpired', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'))
})
afterEach(() => {
vi.useRealTimers()
})
it('returns true for a timestamp in the past', () => {
expect(isExpired(new Date('2025-12-31T00:00:00Z').getTime())).toBe(true)
})
it('returns false for a timestamp in the future', () => {
expect(isExpired(new Date('2026-01-02T00:00:00Z').getTime())).toBe(false)
})
})To find hidden order dependencies, run the suite in random order with npx vitest run --sequence.shuffle. If a test fails only when shuffled, it depends on state that another test left behind.
Determinism: control every outside input
A test is flaky when its result depends on something it doesn't control. Replace each of those inputs with a value the test sets.
| Source of flakiness | Fix |
|---|---|
| `Date.now()`, `new Date()` | `vi.useFakeTimers()` with `vi.setSystemTime()` |
| `setTimeout`, `setInterval` | Fake timers with `vi.advanceTimersByTime()` |
| `Math.random()` | `vi.spyOn(Math, 'random').mockReturnValue(0.5)` |
| Network, file system | `vi.mock()` the module that does the I/O |
| Promises nobody awaited | `await` every promise, or `return` it from the test |
Readability: one behavior per test
- Name each test after the behavior and the expected result, for example "returns false for a timestamp in the future" rather than "test 2".
- Follow Arrange, Act, Assert, as in the cart test above, so that the action being tested stands out.
- Keep one behavior per test. Several
expectcalls are fine if they all check the same behavior. - Assert on outputs and observable effects, not on private details. A test that breaks on every refactor protects nothing.
- Mock only at the edges of your system (network, time, randomness). If a test needs many mocks, the code under test probably has too many dependencies.
- Treat coverage as a map of untested code, not a goal. A line can be covered by a test that asserts nothing about it.
Exercise
A test of pickWinner(players), which uses Math.random(), passes about half the time. A second test file passes on its own but fails when it runs after a test that calls vi.useFakeTimers(). What should you change in each case?
Show answer
In the first test, make the random value fixed with vi.spyOn(Math, 'random').mockReturnValue(0) (or another chosen value) and restore it after the test, either with restoreMocks: true or vi.restoreAllMocks() in afterEach. In the second case, the earlier test leaks fake timers, so add afterEach(() => { vi.useRealTimers() }) wherever fake timers are turned on.
Exercise
Why is "sums the prices of added items" a better test name than "cart works"?
Show answer
It names one specific behavior and its expected result. When it fails, you know which behavior broke without opening the test body.