Spy vs Mock
People think a spy is just another name for a mock, and it is not. A mock is told up front which calls to expect, and it fails the test if they do not come. A spy only writes down every call. The test then looks at that record after the code has run and decides what to check.
Spy (Testing)
A wrapper that watches a real function and notes each call to it.
A spy wraps a real function and records every call, while still letting the real code run. Unlike a mock, it keeps the real behaviour by default. The test can then check how many times the function ran and with what. Jest makes one with jest.spyOn. Spies help when you want the real work done and proof it happened.
Mock (Testing)
A fake part that records how your code called it, so a test can check.
A mock is a test double that records how it was called, so the test can check it. You hand it to your code in place of the real part. After the code runs, you ask the mock: were you called, how many times, and with what? That lets you test that your code sent an email without sending one. Most test tools have mocks built in.
In one line
- Spy (Testing)
- A wrapper that watches a real function and notes each call to it.
- Mock (Testing)
- A fake part that records how your code called it, so a test can check.