What jest.spyOn() Does Differently
jest.spyOn(object, 'methodName') wraps an existing method on a real object, returning a mock function that, unlike a bare jest.fn(), still calls through to the genuine implementation by default. This makes spyOn the right tool when you want to observe how a real object's method is used — its call count, arguments, and return values — without disabling the actual behavior it produces, which matters when the method has side effects your test still relies on, such as internal helper functions the code under test depends on.
Cricket analogy: Placing a hidden speed-gun operator behind the bowler's real action, rather than replacing the bowler entirely, mirrors jest.spyOn() wrapping a real method while still letting it execute.
Spying Without Changing Behavior
A common pattern is spying purely for observation: jest.spyOn(console, 'log') lets you assert that a warning was logged, or jest.spyOn(myModule, 'formatDate') lets you confirm an internal helper was invoked with the right input, all while the method keeps executing normally so any code depending on its real output continues to work correctly. This is especially useful for verifying internal collaboration between functions in the same module without breaking their real interaction.
Cricket analogy: Recording Jasprit Bumrah's actual deliveries while a scout logs each one for later review, without altering his bowling, resembles a spy that calls through to the original implementation.
const utils = require('./utils');
test('spies on a real method call', () => {
const spy = jest.spyOn(utils, 'formatDate');
utils.printReceipt({ date: '2026-01-01' });
expect(spy).toHaveBeenCalledWith('2026-01-01');
spy.mockRestore();
});
test('overrides behavior while spying', () => {
const spy = jest.spyOn(console, 'log').mockImplementation(() => {});
logStartup();
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});Overriding Behavior While Spying
A spy can also be redirected just like a plain mock by chaining .mockImplementation() or .mockReturnValue() onto it, which is useful for silencing noisy output (console.error), making a class prototype method deterministic (Date.prototype.getTime), or forcing a specific branch of code to execute. Because spyOn works against an object's property, it also supports spying on class instance methods and prototype methods directly, e.g. jest.spyOn(UserService.prototype, 'save').
Cricket analogy: Briefing a stand-in commentator to swap the real call for a scripted one only during DRS reviews, while play continues normally otherwise, mirrors overriding a spy's behavior with mockImplementation.
By default jest.spyOn(object, 'method') still calls the original implementation — it only starts faking behavior once you chain .mockImplementation() or .mockReturnValue() onto it, which is the key difference from jest.fn().
Restoring Spies and restoreAllMocks
Because a spy wraps a genuine method, it needs to be undone explicitly with spy.mockRestore() (or jest.restoreAllMocks() in an afterEach) to put the original implementation back in place; this is different from mockReset(), which only strips configured behavior but leaves the object's property replaced by the mock. Setting restoreMocks: true in jest.config.js automates this cleanup, which matters most when spying on shared globals like Date.now or Math.random that other tests also depend on.
Cricket analogy: Sending the scout home after the innings, restoring commentary fully to the live broadcaster, mirrors mockRestore reverting a spied method back to its untouched original.
Spying on getters/setters requires the third argument: jest.spyOn(object, 'value', 'get'). Also, restoreAllMocks() only works on spies created with jest.spyOn() — plain jest.fn() mocks have no original implementation to restore to.
- jest.spyOn(object, 'method') wraps an existing method while still calling through to its real implementation by default.
- Unlike jest.fn(), a spy lets you observe real behavior — useful for verifying a function called console.log or another internal method without stubbing it out.
- Chaining .mockImplementation() or .mockReturnValue() onto a spy overrides its behavior just like a plain mock.
- spy.mockRestore() reinstates the original, unmocked method — something a plain jest.fn() has no equivalent for since it never wrapped anything real.
- jest.restoreAllMocks() restores every spy created with jest.spyOn() in one call, typically used in an afterEach hook.
- Spying on getters or setters requires a third argument, e.g. jest.spyOn(obj, 'value', 'get').
- restoreAllMocks only affects spies with an original implementation to return to; it has no effect on standalone jest.fn() mocks.
Practice what you learned
1. By default, what happens when you call jest.spyOn(obj, 'method') without chaining anything else?
2. How do you make a spy stop calling the real implementation and instead return a fixed value?
3. What does spy.mockRestore() do that mockReset() does not?
4. How do you spy on a getter property named 'total' on an object?
5. Which afterEach call restores every jest.spyOn() spy at once?
Was this page helpful?
You May Also Like
Mock Functions with jest.fn()
Learn how to create, configure, and inspect Jest mock functions to isolate units under test and verify how dependencies are called.
Mocking Modules with jest.mock()
Understand how jest.mock() replaces entire modules with automatic or manual mocks, and how to combine that with jest.requireActual for partial mocking.
Mocking Timers
Learn how to use Jest's fake timers to control setTimeout, setInterval, and Date deterministically instead of waiting on real wall-clock time in tests.