In Jest 30, how does jest.spyOn(object, methodName) differ from assigning jest.fn() to that method, and how is the original put back?
answer
- wrap, do not replace
- the original still runs
- a restore function remembered
- assignment forgets the original
basics
~20 sjest.spyOn swaps object[methodName] for a mock that records calls and, by default, still runs the original; mockRestore or jest.restoreAllMocks puts the original back. Assigning jest.fn() loses the original, so restoring it is the test's own job.
solid answer
~40 s`jest.spyOn(logger, 'info')` installs a mock on the property and remembers how to undo it. Unlike most libraries, the spy calls through to the real method by default, so behaviour is unchanged while every call is recorded; to fake it I chain `mockImplementation` or `mockReturnValue`. `spy.mockRestore()` puts the original back, and `jest.restoreAllMocks()` or the `restoreMocks` config key does it for every spy. Writing `logger.info = jest.fn()` gives the same call record but no memory of the original: `mockRestore()` on that mock only resets it, and the fake stays on the object until I reassign the saved method myself. Jest 30 also lets me write `using spy = jest.spyOn(...)` so the spy is restored when the block ends.
code
javascript · 24 linesconst logger = {
info: message => `logged ${message}`,
};
afterEach(() => {
jest.restoreAllMocks();
});
test('a spy records the call and still runs the original', () => {
const spy = jest.spyOn(logger, 'info');
expect(logger.info('order ord_1 placed')).toBe('logged order ord_1 placed');
expect(spy).toHaveBeenCalledWith('order ord_1 placed');
});
test('a spy can replace the original for one test', () => {
jest.spyOn(logger, 'info').mockImplementation(() => 'silenced');
expect(logger.info('order ord_2 placed')).toBe('silenced');
});
test('the original is back after restoreAllMocks', () => {
expect(jest.isMockFunction(logger.info)).toBe(false);
});go deeper
Remember that jest.spyOn records calls but still runs the real method unless you give it an implementation.
Explain how the spy installs itself on the object, why mockRestore only means something for spies, and how restoreAllMocks and restoreMocks automate it.
Diagnose spies that see nothing because of captured references, and leaks from spies that were never restored or were re-spied with an old record.
Set a team default for restoring spies automatically, and weigh how far spying on shared modules should go before injecting the dependency instead.
## What `jest.spyOn` installs `jest.spyOn(object, methodName)` looks up `object[methodName]`, creates a Jest mock function, puts that mock on the object in place of the method, and keeps a **restore function** that knows how to put the original back. It returns the mock, so the same handle serves for configuring and for asserting. The call record is the ordinary one: `mock.calls`, `mock.results` and the `toHaveBeenCalled...` matchers all work on a spy exactly as they do on `jest.fn()`. ## The spy calls through by default The spy's starting implementation simply calls the original with the same `this` and arguments. That is different behaviour from most other test libraries, where a spy or stub replaces the method outright. In practice: - `jest.spyOn(logger, 'info')` alone records calls and still lets the real logger write its line. - `jest.spyOn(logger, 'info').mockImplementation(() => {})` silences it. - `jest.spyOn(paymentClient, 'charge').mockResolvedValue({ id: 'rcpt_1' })` replaces a network call with a canned result. The call-through passes along the same `this` the caller used, so methods that read instance fields keep working. Spying on a prototype, as in `jest.spyOn(PaymentClient.prototype, 'charge')`, intercepts calls on every instance, including instances created before the spy, because they look the method up through the prototype at call time. A method defined as an arrow-function class field is an own property of each instance instead, so a prototype spy never sees it. Any of the value helpers and `...Once` forms apply, and once a queued value is used up the spy falls back to its default implementation, which is the call-through unless you changed it. ## Putting the original back A spy changes a shared object, so it has to be undone, or the next test inherits it. Jest offers several routes: 1. **`spy.mockRestore()`** runs the restore function: the original method is back on the object, and the spy's record and implementation are reset. 2. **`jest.restoreAllMocks()`**, usually in `afterEach`, restores every spy and every property replaced with `jest.replaceProperty`. 3. **`restoreMocks: true`** in the Jest config runs `jest.restoreAllMocks()` before each test. 4. **The `using` keyword**, supported since **Jest 30**: with a transpiler set up for explicit resource management, `using spy = jest.spyOn(console, 'warn')` restores the spy automatically when the enclosing block ends, as if a `finally` called `mockRestore()`. ## Assigning `jest.fn()` directly | | `jest.spyOn(obj, 'm')` | `obj.m = jest.fn()` | |---|---|---| | Records calls | yes | yes | | Runs the original by default | yes | no, returns `undefined` | | Remembers the original | yes | no | | `mockRestore()` effect | original back on the object | resets the mock; the fake stays | | Covered by `restoreAllMocks` | yes | no | Direct assignment is fine for a throwaway object built inside one test. On a shared module export or a global such as `console`, it leaks into every later test in the file unless the test saved the original and writes it back itself. ## Where spying stops working The source of `jest.spyOn` enforces a few rules, and each one turns up in real debugging: - **The property must exist and hold a function.** Spying on a missing name throws ``Property `x` does not exist in the provided object``. Spying on a number or string throws a `TypeError` that suggests `jest.replaceProperty(object, 'name', value)` instead. - **Getters and setters need an access type.** `jest.spyOn(obj, 'prop', 'get')` or `'set'` spies on an accessor rather than a method. - **Only calls through the property are seen.** The spy replaces `object[methodName]`; code that captured the function earlier, for example `const { info } = logger` at module load, keeps calling the original and the spy records nothing. - **Spying twice returns the same spy.** If the method is already a mock, `jest.spyOn` hands back that existing mock instead of wrapping it again, so its record still holds earlier calls unless it was restored or cleared in between. ## Choosing between them - Reach for **`jest.spyOn`** whenever the method lives on an object that outlives the test: an imported module's exports, a class prototype, `console`, `Date`. - Reach for **`jest.fn()`** when the test owns the dependency, such as a callback or a collaborator passed into a function. - Make restoring automatic, through `afterEach(() => jest.restoreAllMocks())` or `restoreMocks`, rather than trusting every test to call `mockRestore()` itself.
- Why does a jest.spyOn spy on logger.info record nothing when the module under test did const { info } = require('./logger') at load time?The spy replaces the `info` property on the logger object. The module copied the original function into its own `info` binding before the spy existed, so it keeps calling that original and never touches the property. Spy before the module loads, or have the code call `logger.info(...)` through the object.
- How do you spy on a getter such as a config object's timeout property?Pass the access type: `jest.spyOn(config, 'timeout', 'get').mockReturnValue(50)`. Without it, `jest.spyOn` reads the property, finds a value that is not a function and throws. For a plain data property with no getter, `jest.replaceProperty(config, 'timeout', 50)` is the matching tool, and `restoreAllMocks` undoes it.
- jest.spyOn stubs the method out, so the original never runs.
- mockRestore puts back the original of a mock assigned with jest.fn().
- A spy sees calls made through a reference captured before spyOn ran.
- jest.spyOn can wrap a property that holds a plain number.
- Calling jest.spyOn twice on one method stacks two independent spies.
Assumes Jest 30, which added support for disposing a jest.spyOn spy with the using keyword; spyOn's call-through and mockRestore behaviour are not new in 30.