Skip to content
BENIBIX Learn

Spy (Testing)

Development🧪 Testing & QualityTest Doubles

Also known as Spy, Test Spy, spyOn

A wrapper that watches a real function and notes each call to it.

Think of it like

Think of it like a helper. They watch a worker and write down each job.

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.

Definition

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 code

javascript
const spy = jest.spyOn(shop, 'log');
shop.log('paid');
expect(spy).toHaveBeenCalledTimes(1);
The real log runs, and the spy counts the call.

Common mistake

Forgetting to remove a spy after the test. It can leak into the next test and give strange results.

Key takeaways

  1. 1
    Wraps the real thing. The real code still runs.
  2. 2
    Records calls. Count and arguments.
  3. 3
    Clean up after. Restore it when done.

Compare