Mock vs Stub vs Spy in Testing

These are all types of test doubles that stand in for real dependencies, but differ in purpose: a stub returns canned responses, a mock verifies specific int...

Published November 15, 2026

Stubs return canned answers, mocks verify that expected calls happened, and spies wrap real objects to record how they were called. All three are 'test doubles' that replace real dependencies in tests.

The concept

A stub controls inputs: 'when getUser(1) is called, return Ada'. A mock sets expectations and fails the test if they are not met. A spy lets the real code run while recording calls.

Use stubs to isolate the unit, mocks or spies to check interactions such as 'an email was sent'.

What each one does

stub → returns fixed data
mock → returns data + asserts calls were made
spy → real behaviour + records calls

Practical examples

Stub

const repo = { find: () => ({ id: 1, name: 'Ada' }) }
expect(greet(repo, 1)).toBe('Hello Ada')

Mock (Jest)

const mailer = { send: jest.fn() }
await signup('a@x.com', mailer)
expect(mailer.send).toHaveBeenCalledWith('a@x.com', expect.any(String))

Spy

const spy = jest.spyOn(console, 'log')
run()
expect(spy).toHaveBeenCalledTimes(1)

Common mistakes

  • Mocking everything so tests pass but prove nothing.
  • Asserting implementation details.
  • Forgetting to restore spies between tests.

Key takeaways

  • Stub = data, mock = expectations, spy = recording.
  • Test doubles isolate units.
  • Do not over-mock.

FAQ

What is a fake?

A working lightweight implementation, such as an in-memory database.

Do I always need them?

Only for slow or non-deterministic dependencies.

More General articles