| | |

Jest 10 ๐Ÿƒ Spying on Methods โ€” jest.spyOn() and the using keyword in v30

โฑ๏ธ Estimated read: 8 min | |

jest.spyOn(object, "method") creates a mock that wraps an existing method on an object. It records every call, and it calls the original method by default. The difference from jest.fn() is that the spy is attached to a real object and preserves the original behavior unless the test replaces it. Jest 30 adds a second cleanup mechanism: the using keyword, which automatically restores the spy when the block ends, removing the need for a manual mockRestore() or an afterEach in the common case .

This chapter covers the jest.spyOn() API, the using keyword integration, and the restore lifecycle that keeps a spy from leaking into the next test. The sections that follow walk through the spy’s creation, the using declaration, and the restoreMocks configuration that handles the cases where using is not available.

Key point: jest.spyOn(obj, "method") wraps the method and calls the original by default; Jest 30 supports using spy = jest.spyOn(...) to restore the spy automatically at the end of the block, and mockRestore() or restoreMocks: true handles the cases where using is not used.


a. Creating a spy and the call-through default

jest.spyOn(object, "method") returns a spy that is installed on the object. The spy records the call and, by default, invokes the original method with the same arguments and returns its result. This is the difference from jest.fn(), which has no original to call .

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

test("spies on add without changing it", () => {
  const spy = jest.spyOn(calculator, "add");

  const result = calculator.add(2, 3);

  expect(result).toBe(5); // original still runs
  expect(spy).toHaveBeenCalledWith(2, 3); // call recorded
});

The spy is installed on the object, not on a copy. A call to calculator.add() after jest.spyOn goes through the spy, and the spy’s call history records it. The original method is still callable, which is why the result is 5.

The spy works on any object with a method: a class instance, a module’s exported object, console, window, document. The jest.spyOn(console, "log") spy is the standard way to assert that code logged a message without polluting the test output.

const logSpy = jest.spyOn(console, "log").mockImplementation(() => {});
// code that calls console.log
expect(logSpy).toHaveBeenCalledWith("expected message");

The mockImplementation(() => {}) is what silences the log while still recording the call. Without it, the spy calls the original console.log and the message appears in the test output.


b. The using keyword in Jest 30

Jest 30 adds support for JavaScript’s Explicit Resource Management syntax. A spy created with jest.spyOn() implements the [Symbol.dispose]() method, which means it can be declared with using instead of const. When the block ends, the spy is automatically restored .

test("logs a warning", () => {
  using spy = jest.spyOn(console, "warn");
  doSomethingWarnWorthy();
  expect(spy).toHaveBeenCalled();
  // spy.mockRestore() is called automatically when the block ends
});

The using declaration is block-scoped, like const. The engine calls spy[Symbol.dispose]() when execution leaves the block, which restores the original method. This is the same mechanism the Explicit Resource Management proposal defines for any disposable resource: the using declaration binds the cleanup to the scope’s lifetime .

The using form requires the environment to support the syntax. It is a relatively new JavaScript feature, and a project on an older Node version or an older TypeScript target may not have it. When the syntax is not available, the afterEach with jest.restoreAllMocks() or the restoreMocks: true config is the fallback.

The using declaration is the cleanest form for a spy that is scoped to a single test. It removes the need for the explicit mockRestore() at the end of the test, and it guarantees that the restore happens even if the test throws before reaching the end.


c. Restoring and the configuration

The mockRestore() method removes the spy and restores the original method. The jest.restoreAllMocks() function restores every spy created with jest.spyOn(), and the restoreMocks: true config option runs it before each test .

// jest.config.js
module.exports = {
  restoreMocks: true,
};

The distinction that matters is restoreMocks versus resetMocks. restoreMocks restores the original method, so the spy is removed and the method behaves as it did before the spy. resetMocks clears the implementation but leaves the spy installed, so the method returns undefined unless the test configures it again.

The using keyword and restoreMocks are complementary. The using declaration restores the spy at the end of the block in which it was declared, which is the per-test scope. The restoreMocks option restores every spy before each test, which catches a spy that was created outside a using block or a spy that was created in a beforeEach. A suite that uses both is safe regardless of how the spy was declared.

The jest.spyOn() and jest.fn() distinction is the same as in Vitest: the spy is attached to a real object and calls the original by default, and the mock is standalone. The using keyword is the Jest-specific addition that makes the spy’s lifecycle declarative .


Complete Example Session

// ============================================
// PART 1: THE OBJECT UNDER TEST
// ============================================
// src/notifier.js
const notifier = {
  send(email, message) {
    console.log(`Sending to ${email}: ${message}`);
  },
};

function notifyUser(email) {
  notifier.send(email, "Welcome!");
}

module.exports = { notifier, notifyUser };

// ============================================
// PART 2: THE SPY (CALL-THROUGH)
// ============================================
const { notifier, notifyUser } = require("./notifier");

describe("notifyUser", () => {
  test("calls notifier.send with the email", () => {
    const spy = jest.spyOn(notifier, "send").mockImplementation(() => {});

    notifyUser("a@b.com");

    expect(spy).toHaveBeenCalledWith("a@b.com", "Welcome!");

    spy.mockRestore();
  });
});

// ============================================
// PART 3: THE using KEYWORD
// ============================================
describe("using", () => {
  test("restores automatically", () => {
    using spy = jest.spyOn(console, "warn");
    console.warn("something");
    expect(spy).toHaveBeenCalledWith("something");
    // restored when the test ends
  });
});

// ============================================
// PART 4: THE CONFIG-BASED RESTORE
// ============================================
// jest.config.js
// module.exports = { restoreMocks: true };

The parts covered the call-through spy, the using declaration, and the config-based restore.


Quick Reference

Spy API

CallEffect
jest.spyOn(obj, "method")Wraps, records, calls original
.mockImplementation(fn)Replaces the body
.mockReturnValue(v)Replaces the return
.mockResolvedValue(v)Replaces the return with a resolved Promise
.mockRestore()Removes the spy, restores original
using spy = ...Auto-restores at block end

Restore Options

OptionEffect
restoreMocks: truejest.restoreAllMocks() before each test
mockRestore()Restores one spy
jest.restoreAllMocks()Restores all spies

using Requirements

RequirementDetail
Syntaxusing spy = jest.spyOn(...)
ScopeBlock-scoped
Cleanup[Symbol.dispose]() at block exit
EnvironmentNeeds Explicit Resource Management support

Best Practices

โœ… Do This:

// Use using for a scoped spy
using spy = jest.spyOn(console, "warn");                      // โœ…

// Restore explicitly when using is not available
spy.mockRestore();                                             // โœ…

// Configure the global restore
module.exports = { restoreMocks: true };                       // โœ…

โŒ Don’t Do This:

// Spy without restoring
jest.spyOn(obj, "method"); // leaks into the next test           // โŒ

// Use mockReset expecting the original restored
spy.mockReset(); // spy still installed, returns undefined       // โŒ

// Assume using works without the syntax support
using spy = ...; // syntax error in older environments           // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Next test gets mocked behaviorSpy not restoredrestoreMocks: true or using
mockReset does not restoreClears implementation, not the spyUse mockRestore()
using syntax errorEnvironment lacks supportUse afterEach restore
Original still logsNo mockImplementationSilence the original

Real-World Examples

1. Call-through spy

const spy = jest.spyOn(calculator, "add");
calculator.add(1, 2);
expect(spy).toHaveBeenCalledWith(1, 2);

2. Replace return

jest.spyOn(api, "fetchUser").mockResolvedValue({ id: "1" });

3. Silence console

jest.spyOn(console, "log").mockImplementation(() => {});

4. Restore

spy.mockRestore();

5. Global restore

module.exports = { restoreMocks: true };

6. using declaration

using spy = jest.spyOn(console, "warn");

7. Getter spy

jest.spyOn(obj, "prop", "get").mockReturnValue(42);

8. Throw

jest.spyOn(api, "post").mockRejectedValue(new Error("fail"));

9. Once

jest.spyOn(api, "get").mockReturnValueOnce(1).mockReturnValue(2);

10. Explicit restore in afterEach

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

Visual

Spy Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  jest.spyOn(obj, "method")                              โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Spy installed, calls original by default               โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ”œโ”€โ”€โ–บ mockImplementation โ†’ original replaced     โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Call recorded in mock.calls                            โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  mockRestore() or using โ†’ original restored             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The using Keyword

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  test("...", () => {                                    โ”‚
โ”‚    using spy = jest.spyOn(console, "warn");             โ”‚
โ”‚    console.warn("something");                           โ”‚
โ”‚    expect(spy).toHaveBeenCalled();                      โ”‚
โ”‚  });                                                    โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Block ends โ†’ spy[Symbol.dispose]() โ†’ restore           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Restore vs Reset

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  mockRestore()                                          โ”‚
โ”‚    history cleared                                      โ”‚
โ”‚    implementation: original                             โ”‚
โ”‚    spy removed                                          โ”‚
โ”‚                                                         โ”‚
โ”‚  mockReset()                                            โ”‚
โ”‚    history cleared                                      โ”‚
โ”‚    implementation: undefined                            โ”‚
โ”‚    spy still installed                                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Leak

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Test 1: jest.spyOn(api, "get").mockReturnValue("mocked")โ”‚
โ”‚         โ†’ api.get() returns "mocked"                    โ”‚
โ”‚                                                         โ”‚
โ”‚  Test 2: api.get()                                      โ”‚
โ”‚         โ†’ still returns "mocked" (leaked)               โ”‚
โ”‚                                                         โ”‚
โ”‚  Fix: using, restoreMocks: true, or mockRestore()       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Createjest.spyOn(obj, "method")
Default behaviorCalls the original
Replace.mockImplementation(fn)
Restore.mockRestore()
Auto-restore (v30)using spy = jest.spyOn(...)
Global restorerestoreMocks: true
Getter spyjest.spyOn(obj, "prop", "get")

Key takeaways:

  • A spy wraps an object’s method and calls the original by default. The difference from jest.fn() is that the spy is attached to a real object, and the original behavior is preserved unless the test replaces it.
  • Jest 30 supports using for automatic restore. using spy = jest.spyOn(console, "warn") restores the spy when the block ends, removing the need for an explicit mockRestore() .
  • mockReset is not mockRestore. Reset clears the history and the implementation but leaves the spy installed, so the method returns undefined. Restore removes the spy and returns the original.
  • restoreMocks: true is the safe default. It runs jest.restoreAllMocks() before each test, so no spy survives into the next test, regardless of how it was declared.
  • Use jest.spyOn() for single methods and jest.fn() for standalone mocks. The spy is the lighter-weight option when the test can access the object directly, and the using keyword makes its lifecycle declarative.

Remember: A spy is a wrapper, not a replacement. It records the call and calls the original until the test says otherwise. The restore is the part that keeps the wrapper from becoming permanent. Use using when the environment supports it, mockRestore() when it does not, and restoreMocks: true as the safety net. The leak is silent: the next test passes or fails against a method that is not the real one.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!