Spying on Existing Functions with jest.spyOn
You'll learn how to monitor real methods without fully replacing them, giving you insight into how code actually behaves.
What Is jest.spyOn?
While jest.fn() creates a brand-new mock function, sometimes you want to observe an existing method on a real object—without destroying its original behavior. That's where jest.spyOn() shines. It wraps the real function, tracking all calls while still executing the original code (unless you choose to override it).
Think of it like attaching a security camera to a door: you can watch everyone who enters and exits, but the door still works normally.
How It Works
jest.spyOn() takes two arguments: the object and the method name as a string.
const user = {
getName: () => "Alice"
};
const spy = jest.spyOn(user, "getName");
user.getName(); // Still returns "Alice"
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(1);
The original getName still executes, but now you can verify it was called.
Replacing Behavior Optionally
You can override the implementation while keeping the spy active:
jest.spyOn(console, "log").mockImplementation(() => {});
console.log("test"); // Suppressed, but tracked
expect(console.log).toHaveBeenCalledWith("test");
This is perfect for silencing noisy functions during tests without losing call tracking.
Restoring Original Behavior
Always clean up spies to avoid test pollution:
afterEach(() => {
jest.restoreAllMocks();
});
Key Takeaway: jest.spyOn() lets you observe and optionally override real methods, preserving original behavior by default while giving you full visibility into how functions are used—ideal for testing code that relies on existing objects or built-in APIs.