CodePark/ questions / Mocks, stubs, spies & fakes
START PRACTICINGPRACTICE
Backend question · Backend testing › Mocks, stubs, spies & fakes

Explain the test doubles dummy, stub, spy, mock and fake, with a backend example of each.

A test double is anything that takes the place of a real dependency in a test. The name comes from Gerard Meszaros. There are five kinds:

  • A dummy only fills a parameter and is never used. Example: a logger that this code path never calls.
  • A stub returns fixed, prepared answers. Example: a rates.get() that always resolves 1.1.
  • A spy is a stub that also records its calls. Afterwards you can check that mailer.send got the right address.
  • A mock is set up with expectations about the calls it should receive. It fails the test if those calls don't happen.
  • A fake is a working but simpler implementation. Example: an in-memory UsersRepository that stores data in a Map.

In Jest, jest.fn() can act as a stub, a spy or a mock. It depends on how you use it.

Stubs and fakes help you check state (the result). Spies and mocks help you check interactions (which calls happened).

  • A dummy fills a parameter and is never used.
  • A stub returns prepared answers. A spy also records its calls.
  • A mock has expectations about its calls set in advance, and it checks the interactions.
  • A fake is a working, lightweight implementation, such as an in-memory repository.