# Spy (Testing)

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

**Field:** Software Development  
**Category:** Testing & Quality  
**Also known as:** Spy, Test Spy, spyOn

## Think of it like

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

## 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

Lucy wraps her logger in a spy. The real log line is still written, and the test checks it was called once with paid.

## 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.

## Why it matters

You get the real result and a record of the call, in one test.

## Common mistake

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

## Three principles

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

## Related terms

- [Test Double](https://learn.benibix.com/term/development/test-double)
- [Mock (Testing)](https://learn.benibix.com/term/development/mock)
- [Jest](https://learn.benibix.com/term/development/jest)
- [Function Call](https://learn.benibix.com/term/development/function-call)

## Told apart from

- [Spy vs Mock](https://learn.benibix.com/compare/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.

---

Source: https://learn.benibix.com/term/development/spy
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
