Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 30 ยท Mocking

Spying with jest.spyOn

Use jest.spyOn to watch or replace methods on real objects: clear vs reset vs restore, restoreMocks config, spying on console and Math.random, with runnable stand-ins.

A mock function made with jest.fn() is a new function you hand to your code. Sometimes the function you care about already exists on an object you do not control: console.log, Math.random, Date.now, a method on a class, or a function exported by a module. You cannot pass a mock in, because the code under test looks the function up by itself.

jest.spyOn(object, "methodName") solves this. It replaces the method with a mock that, by default, still calls the original, so you can watch a real method. You can also change its behavior and, importantly, put the original back when the test is done. This lesson explains how spies work, the three ways to reset them, and common targets such as console and Math.random.

The real jest.spyOn needs Jest, so the Jest code here is read-only. The runnable parts use a small stand-in that does the same swap-and-restore trick, and Node's own mock.method. Each is labelled as a stand-in.

What spyOn does

Wraps The method is replaced by a mock that calls the original.
Overrides Optionally change what it returns.
Restores mockRestore puts the original back.

The object's own property is swapped, so always restore it.

1 / 2

Spying on an object method

Imagine a small calculator object and a function that uses it:

JavaScript
const calculator = {
  add(a, b) {
    return a + b;
  },
};

function total(prices) {
  return prices.reduce((sum, price) => calculator.add(sum, price), 0);
}

A spy watches calculator.add without changing the result:

JavaScript
test("total adds every price", () => {
  const spy = jest.spyOn(calculator, "add");

  expect(total([5, 10, 20])).toBe(35);   // the real add still runs
  expect(spy).toHaveBeenCalledTimes(3);
  expect(spy).toHaveBeenNthCalledWith(2, 5, 10);

  spy.mockRestore();                     // put the original back
});

The spy is a normal mock function, so everything from Mock Functions with jest.fn applies: mock.calls, toHaveBeenCalledWith, mockReturnValue and the rest.

To change behavior while spying, chain a mock method:

JavaScript
jest.spyOn(calculator, "add").mockReturnValue(100);
expect(total([1, 2])).toBe(100);

jest.spyOn only works on properties that exist and are functions. Spying on a missing method throws an error, which is a helpful typo check. For getters and setters there is a third argument: jest.spyOn(obj, "prop", "get").

A spy swaps a property on the real object. If your code imported the function by name (import { add } from "./math"), the code holds its own reference and the swap on the object may not be seen. Mocking Modules covers that case.

Clearing, resetting and restoring

Spies and mocks keep state between tests, so a call from one test can leak into the next. Jest has three levels of cleanup, from gentle to complete:

Method Clears calls and results Removes mocked return values/implementations Reinstalls the original method
mockClear() yes no no
mockReset() yes yes no
mockRestore() yes yes yes (for spyOn spies)

There are matching global versions: jest.clearAllMocks(), jest.resetAllMocks() and jest.restoreAllMocks(). In recent Jest versions, restoreAllMocks only affects spies made with jest.spyOn, not plain jest.fn() mocks, so check the release notes of the version you use if you rely on this detail.

You can also do this for every test automatically in your config file:

JavaScript
// jest.config.js
module.exports = {
  clearMocks: true,    // mockClear before each test
  resetMocks: false,   // mockReset before each test
  restoreMocks: true,  // mockRestore before each test
};

A reasonable default for most projects is restoreMocks: true. It stops one test's spy from changing what the next test sees, which is the most common cause of confusing failures. More on that in Test Isolation and Shared State.

If you prefer to be explicit, restore in a hook:

JavaScript
afterEach(() => {
  jest.restoreAllMocks();
});

Spying on console

Code often logs warnings or errors. You may want to assert that a warning was printed, or keep noisy output out of the test report. Spy on console and silence it by giving the spy an empty implementation:

JavaScript
test("warns about a negative amount", () => {
  const warn = jest.spyOn(console, "warn").mockImplementation(() => {});

  chargeCustomer(-5);

  expect(warn).toHaveBeenCalledTimes(1);
  expect(warn).toHaveBeenCalledWith(expect.stringContaining("negative"));
  warn.mockRestore();
});

Without mockImplementation, the real console.warn would still print. With it, nothing prints and you still get the call history. Do not forget to restore, or every later test in the file will silently swallow its own warnings.

If a test fails and prints nothing helpful, check whether an earlier spy on console.log is still installed. A missing restore is a very common reason for "my debug output vanished".

Making random and time predictable

Two other popular spy targets are Math.random and Date.now. Replacing them makes unpredictable code deterministic:

JavaScript
test("picks the first item when random returns 0", () => {
  jest.spyOn(Math, "random").mockReturnValue(0);

  expect(pickOne(["a", "b", "c"])).toBe("a");
});

For dates and timers there are better tools, described in Mocking Timers, Dates and HTTP.

Stand-in 1: a spy built by hand

A spy is a three-step trick: remember the original, put a recording wrapper in its place, and provide a way to undo it. The stand-in below does exactly that. It is NOT Jest's implementation (real Jest also handles getters, setters, classes and symbol keys), but the swap-and-restore idea is the same.

Node.js spyOn stand-in: swap and restore

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the three cleanup lines carefully. After mockClear, the call list is empty but the override stays. After mockReset, the override is gone and the spy calls through again. Only mockRestore removes the wrapper itself.

Stand-in 2: node:test mock.method with console

Node's mock.method(object, "name", implementation?) is the same idea, with .mock.restore() to undo it. This is real Node code, shown here as a stand-in for Jest's spy on console. Because the spy replaces console.warn, the example prints through console.log, which it leaves alone.

Node.js Spying on console.warn with node:test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The silenced warn prints nothing yet remembers its single call. Once restored, console.warn is the real function again.

spyOn or jest.fn?

  • Use jest.fn() when you control how the function is passed in (a callback or an injected dependency).
  • Use jest.spyOn when the function lives on an existing object and the code under test finds it there.
  • Use jest.mock (next lesson) when the code imports the function from another module.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. By default, what does a jest.spyOn spy do when it is called?

    A fresh spy wraps the original: it records the call and then runs the real method unless you override it.
  2. 2. Which method clears calls AND reinstalls the original method on the object?

    mockRestore does everything mockReset does and also puts the original method back. mockClear only forgets the call history.
  3. 3. You spy on console.warn with mockImplementation(() => {}) and forget to restore it. What happens in later tests in that file?

    Unless restoreMocks is enabled or you restore manually, the replaced method stays in place for the rest of the file.
  4. 4. What happens if you call jest.spyOn(obj, "nope") and obj has no method named nope?

    spyOn requires an existing function property, which also catches typos in the method name.

Summary

  • jest.spyOn(object, "method") replaces a method with a recording mock that calls the original by default.
  • Chain mockReturnValue or mockImplementation to change what the spy does.
  • mockClear forgets calls, mockReset also drops mocked behavior, and mockRestore also reinstalls the original method.
  • Set restoreMocks: true in the config (or restore in afterEach) so spies never leak between tests.
  • Spying on console with an empty implementation silences output while still letting you assert on it.

Next, learn what to do when the function you need to replace is imported from another file in Mocking Modules.