Spy
In one line
A spy watches a real function and records its calls (arguments, return values, call count) while still running the original behavior.
In simple words
A spy is like a security camera on a function. It doesn't replace the function — the real function still runs. But the spy records everything: how many times it was called, what arguments were passed each time, and what it returned.
Spies are useful when you want to verify that your code calls a certain function (like a logging function or an analytics tracker) without changing that function's behavior. The real function runs normally, and you can check afterwards that it was called correctly.
In Jest, you create spies with jest.spyOn(object, 'methodName').
Example
const spy = jest.spyOn(console, 'log');
console.log('hello');
console.log('world');
expect(spy).toHaveBeenCalledTimes(2);
expect(spy).toHaveBeenCalledWith('hello');
spy.mockRestore(); // restore originalThe spy records console.log calls while still logging. We verify it was called twice with 'hello' first.
Common confusions
Confused with: Mock
The difference: A spy wraps and observes the original function (which still runs); a mock replaces the function entirely with fake behavior.
Related terms
Related Resources
Related Lessons
- Stubs and Spies
Understanding test doubles.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.