Code Reference

Spies

Jest · Reference cheat sheet

Spies

Jest · Reference cheat sheet


📋 Overview

jest.spyOn(object, method) wraps a real method to assert calls while optionally keeping the original implementation. Prefer spies when you need partial observation.

🔧 Core concepts

APIEffect
jest.spyOn(obj, 'm')Track calls
mockImplementationReplace body
mockRestorePut original back
mockClearClear call history
mockResetClear history + implementation

Spies are mocks; matchers like toHaveBeenCalledWith apply.

💡 Examples

Observe without changing:

const log = jest.spyOn(console, 'log').mockImplementation(() => {});
doWork();
expect(log).toHaveBeenCalledWith('done');
log.mockRestore();

Replace temporarily:

const spy = jest
  .spyOn(Date, 'now')
  .mockReturnValue(1_700_000_000_000);
expect(Date.now()).toBe(1_700_000_000_000);
spy.mockRestore();

Class method:

const spy = jest.spyOn(User.prototype, 'save').mockResolvedValue(undefined);
await user.save();
expect(spy).toHaveBeenCalled();

Cleanup in afterEach:

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

Call order:

expect(fnA.mock.invocationCallOrder[0]).toBeLessThan(
  fnB.mock.invocationCallOrder[0],
);

⚠️ Pitfalls

  • Spying on non-configurable properties / some ESM bindings.
  • Leaving console spies mocked and hiding useful output.
  • mockReset vs mockRestore confusion — restore for spies.
  • Spying after the module cached a bound original function.
  • Asserting call order in parallel async code.

On this page