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 resolves1.1. - A spy is a stub that also records its calls. Afterwards you can check that
mailer.sendgot 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
UsersRepositorythat stores data in aMap.
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.
Read more