Sub topic 16
Writing Isolated, Deterministic, Readable Tests
Earlier chapters covered Vitest's individual tools: matchers, hooks, mocks, fake timers, configuration, and coverage. This chapter shows how to combine them into a suite you can trust and maintain. It assumes you are comfortable with describe/it, lifecycle hooks, vi.fn, vi.spyOn, vi.mock, and fake timers.
A maintainable unit test has three properties:
- Isolated: the result does not depend on other tests, on the order they run in, or on state left behind by earlier tests.
- Deterministic: the same code gives the same result on every run, on every machine.
- Readable: a person seeing a failure for the first time can tell what behavior broke and why.
Isolation: No Shared Mutable State
The most common isolation bug is an object created once and changed by several tests. The tests pass when run in file order and fail when run alone with .only or in a shuffled order.
Create fresh state per test
Build the object under test in beforeEach, or inside each test, so every test starts from a known state.
import { describe, it, expect, beforeEach } from 'vitest'
function createCart() {
const items = []
return {
add(item) {
items.push(item)
},
count() {
return items.length
},
}
}
describe('cart', () => {
let cart
beforeEach(() => {
cart = createCart()
})
it('starts empty', () => {
expect(cart.count()).toBe(0)
})
it('counts added items', () => {
cart.add({ sku: 'A' })
expect(cart.count()).toBe(1)
})
})If cart were created once at the top of the file, "starts empty" would fail whenever it ran after "counts added items". Use beforeAll only for setup that is expensive and read-only, such as loading a large fixture file that no test modifies.
Undo every replacement
Spies, stubbed globals, and environment variables outlive the test that created them unless you restore them. You could call vi.restoreAllMocks() in an afterEach in every file, but it is safer to let the configuration do it for the whole suite:
// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
restoreMocks: true,
unstubGlobals: true,
unstubEnvs: true,
sequence: {
shuffle: true,
},
},
})restoreMocksputs back the original implementations of spies created withvi.spyOnbefore each test.unstubGlobalsandunstubEnvsundovi.stubGlobalandvi.stubEnvafter each test. Use those two helpers instead of assigning toglobalThisorprocess.envdirectly, because a direct assignment is never undone.sequence.shuffleruns files and tests in random order. Hidden dependencies between tests then show up as failures instead of staying hidden.
Determinism: Control Every Input
A test is flaky when it passes or fails without any code change. Flakiness almost always comes from an input the test does not control. The usual sources are the clock, randomness, the network, real timers, and test order.
Inject time and randomness
The cleanest fix is to make the hidden input a parameter, with a default for production code:
// order.js
import { randomUUID } from 'node:crypto'
export function createOrder(
items,
{ now = () => new Date(), makeId = () => randomUUID() } = {},
) {
const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0)
return { id: makeId(), createdAt: now().toISOString(), total }
}// order.test.js
import { describe, it, expect, vi, afterEach } from 'vitest'
import { createOrder } from './order.js'
describe('createOrder', () => {
afterEach(() => {
vi.useRealTimers()
})
it('uses the injected clock and id generator', () => {
const order = createOrder([{ price: 5, quantity: 2 }], {
now: () => new Date('2026-01-01T00:00:00Z'),
makeId: () => 'order-1',
})
expect(order).toEqual({
id: 'order-1',
createdAt: '2026-01-01T00:00:00.000Z',
total: 10,
})
})
it('uses the faked system time when no clock is injected', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-03-15T12:00:00Z'))
const order = createOrder([{ price: 1, quantity: 3 }])
expect(order.createdAt).toBe('2026-03-15T12:00:00.000Z')
expect(order.id).toEqual(expect.any(String))
})
})The second test shows the fallback for code you cannot change: fake timers also fake Date, so vi.setSystemTime fixes the clock. The random id cannot be predicted, so the test asserts only its type with expect.any(String). Asserting the exact id would make the test fail on every run.
Avoid real waiting
Never use a real setTimeout to "give the code time to finish". A wait that works on your laptop will time out on a busy CI machine. Await the promise directly, or use fake timers with vi.advanceTimersByTime, as shown in earlier chapters.
Readability: Tests as Specifications
Name the behavior, not the function
A test name should read as a sentence that states a requirement. When it fails, the report should explain the problem without anyone opening the file.
| Weak name | Better name |
|---|---|
| `createOrder works` | `createOrder totals price times quantity for each item` |
| `test 2` | `rejects an order with no items` |
| `handles error` | `returns null when the API responds with 404` |
Arrange, Act, Assert
Arrange-Act-Assert is a layout for each test body. You set up inputs (arrange), make one call to the code under test (act), then check the result (assert). Separate the three parts with blank lines, as in the createOrder tests above. If a test needs several act steps, it is usually testing several behaviors and should be split.
Use factories for test data
Large inline object literals hide the one field that matters to the test. A factory function, often called a builder, supplies valid defaults and lets each test override only the field it cares about:
import { it, expect } from 'vitest'
function buildUser(overrides = {}) {
return { id: 1, name: 'Ada', role: 'member', active: true, ...overrides }
}
function canEdit(user) {
return user.active && user.role === 'admin'
}
it('lets active admins edit', () => {
expect(canEdit(buildUser({ role: 'admin' }))).toBe(true)
})
it('blocks inactive admins', () => {
expect(canEdit(buildUser({ role: 'admin', active: false }))).toBe(false)
})Keep logic out of tests
Loops, conditionals, and calculations in a test can contain bugs of their own. A test that computes expected = a + b can repeat the same mistake as the code it checks. Write literal expected values. When you need many cases, use test.each instead of a loop.
Pick the most specific matcher
expect(list.length === 3).toBe(true) fails with "expected false to be true". expect(list).toHaveLength(3) fails with the actual length. Specific matchers produce failure messages you can act on.
Test Behavior, Mock at Boundaries
Over-mocking makes tests brittle. A test that asserts which internal helper was called, in what order, breaks when you refactor, even though the behavior stays the same. Use these guidelines:
- Assert on return values, thrown errors, and visible side effects first.
- Mock only at boundaries you do not control or that are slow or unpredictable: the network, the file system, the clock, and third-party services.
- Use
toHaveBeenCalledWithwhen the call itself is the behavior, such as "sends an email to this address". Don't use it to pin down internal steps. - If a test needs five mocks, the unit under test probably has too many dependencies. Treat that as a design signal.
| Smell | Likely cause | Fix |
|---|---|---|
| Passes alone, fails in the full suite | Shared mutable state or unrestored mocks | Fresh state in `beforeEach`, `restoreMocks: true` |
| Fails near midnight or month end | Reads the real clock | Inject a clock or `vi.setSystemTime` |
| Breaks on every refactor | Asserts on implementation details | Assert on outputs and boundary calls |
| Slow suite | Real timers or real I/O | Fake timers, `vi.mock` at the boundary |
| Hard to tell what failed | Vague names, generic matchers | Behavior names, specific matchers |
Exercise
A test calls process.env.API_URL = 'http://test' and later tests in other files start hitting http://test. What change fixes this without adding cleanup code to every file?
Show answer
Replace the direct assignment with vi.stubEnv('API_URL', 'http://test') and set unstubEnvs: true in the test section of vitest.config.js. Vitest then restores the original environment value after each test.
Exercise
A function isWeekend() calls new Date().getDay(). Its test passes on Saturdays and fails on other days. Give two ways to make the test deterministic.
Show answer
First, refactor isWeekend to accept a date or a now function with a default of () => new Date(), and pass a fixed date in the test. Second, without changing the code, call vi.useFakeTimers() and vi.setSystemTime(new Date('2026-11-28T12:00:00Z')) (a Saturday) in the test, then restore real timers in afterEach.
Exercise
A test for checkout() mocks calculateTax, applyDiscount, and formatReceipt, and asserts they are called in that order. A teammate merges discount and tax into one helper, and the test fails even though checkout totals are unchanged. How should the test be rewritten?
Show answer
Remove the mocks for internal helpers and assert on what checkout() returns (the total and the receipt content) for given inputs. Keep mocks only for external boundaries such as a payment API, and assert on those calls only where the call is the required behavior.