Testing & Code Quality

Mocking & Test Doubles

Mocks, stubs, fakes, spies, and fixtures replace real collaborators so tests can control inputs, isolate behavior, avoid slow dependencies, and observe important interactions.
  • A stub returns controlled data
  • A fake has working simplified behavior
  • A spy records interactions
  • A mock encodes expectations
  • Mock at system boundaries, not every function call
Test doubles
DoublePurposeExample
StubReturn predefined valuefake API response
FakeSimplified working implementationin-memory repo
SpyRecord callswas callback called?
MockPre-programmed expectationmust call save once
FixtureReusable test datasample user object
Fake repository
function createFakeUserRepo() {
  const users = new Map()
  return {
    async save(user) {
      users.set(user.id, user)
    },
    async findById(id) {
      return users.get(id) ?? null
    },
  }
}
A fake can support several tests without making every interaction brittle.
Sources
  • Vitest DocumentationMocking
  • Node.js Documentation and Learn Node.jsMocking in tests
  • ESLint DocumentationTesting integrations