Skip to content
BENIBIX Learn

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.

Development🧪 Testing & Quality

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.

Example
Lucy wraps her logger in a spy. The real log line is still written, and the test checks it was called once with paid.
Why it matters
You get the real result and a record of the call, in one test.
Full entry
Development🧪 Testing & Quality

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.

Example
Emma's test gives her sign-up code a mock email sender. The test then checks the mock was called once, with emma@example.com.
Why it matters
Some results never come back as a value, like an email sent. A mock lets you check them anyway.
Full entry

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.