| | |

Jest 12 ๐Ÿƒ Mock Cleanup โ€” clearAllMocks vs resetAllMocks vs restoreAllMocks

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

Jest has three mock cleanup functions and three config options that call them automatically, and the difference between them is what they reset. jest.clearAllMocks() clears the call history but keeps the implementation. jest.resetAllMocks() clears the call history and the implementation. jest.restoreAllMocks() restores the original method for a spy created with jest.spyOn(). The names are close enough that a test can pass with the wrong one and fail with the right one, and the configuration option that calls the wrong function produces a suite that reconfigures every mock in every test.

This chapter covers the three functions, the config options that call them, and the spy versus standalone mock difference that determines whether the reset restores the original. The sections that follow walk through the clear, the reset, and the restore, and the configuration that automates each one.

Key point: clearAllMocks clears history, resetAllMocks clears history and implementation, and restoreAllMocks restores the original for spies; the corresponding config options (clearMocks, resetMocks, restoreMocks) call them before each test, and restoreMocks: true is the safe default for a suite that uses jest.spyOn().


a. clearAllMocks and the call history

jest.clearAllMocks() resets the call history of every mock: mock.calls, mock.results, mock.instances, and the related properties become empty. The implementation is not changed, so a mock that returns 42 still returns 42 after the clear.

const fn = jest.fn().mockReturnValue(42);

fn();
expect(fn).toHaveBeenCalledTimes(1);

jest.clearAllMocks();

expect(fn).not.toHaveBeenCalled(); // history cleared
expect(fn()).toBe(42);             // implementation kept

The clearAllMocks() is the lightest reset. It is the correct choice for a mock that is configured once at module scope and called by multiple tests, because the configuration survives the clear and each test starts with an empty history.

The clearMocks: true config option calls jest.clearAllMocks() before each test. It is the setting for a suite where the mocks are configured once and only the call history needs to be reset.

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

The per-mock mockClear() is the same operation for a single mock. The jest.clearAllMocks() is the global version, and the clearMocks config option is the automatic version.


b. resetAllMocks and the implementation

jest.resetAllMocks() clears the call history and the implementation. A mock that returned 42 returns undefined after the reset, and a mock created with jest.spyOn() no longer calls the original method.

const fn = jest.fn().mockReturnValue(42);

fn();
jest.resetAllMocks();

expect(fn).not.toHaveBeenCalled(); // history cleared
expect(fn()).toBeUndefined();      // implementation cleared

The spy behavior is the detail that differs from Vitest. In Jest, jest.resetAllMocks() on a spy clears the implementation but leaves the spy installed, so the method returns undefined until the test configures it again. In Vitest, mockReset() on a spy restores the original method, which is the behavior that makes a migrated test behave differently.

const obj = { greet: (name) => `Hello, ${name}` };
const spy = jest.spyOn(obj, "greet").mockReturnValue("mocked");

jest.resetAllMocks();

expect(obj.greet("Ana")).toBeUndefined(); // spy still installed

The resetMocks: true config option calls jest.resetAllMocks() before each test. It is the setting for a suite where every test configures its own mocks and the implementation should not persist.


c. restoreAllMocks and the spy removal

jest.restoreAllMocks() restores the original method for every spy created with jest.spyOn(). The object’s method is the original function again, and the spy is no longer installed.

const spy = jest.spyOn(obj, "greet").mockReturnValue("mocked");

jest.restoreAllMocks();

expect(obj.greet("Ana")).toBe("Hello, Ana");

The restoreMocks: true config option calls jest.restoreAllMocks() before each test. It is the safest default for a suite that uses jest.spyOn(), because the spy does not leak into the next test regardless of how it was declared.

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 per-mock mockRestore() is the same operation for a single spy. The jest.restoreAllMocks() is the global version, and the restoreMocks config option is the automatic version.


Complete Example Session

// ============================================
// PART 1: clearAllMocks
// ============================================
describe("clear", () => {
  test("keeps the implementation", () => {
    const fn = jest.fn().mockReturnValue(42);
    fn();
    jest.clearAllMocks();
    expect(fn).not.toHaveBeenCalled();
    expect(fn()).toBe(42); // still returns 42
  });
});

// ============================================
// PART 2: resetAllMocks
// ============================================
describe("reset", () => {
  test("clears the implementation", () => {
    const fn = jest.fn().mockReturnValue(42);
    jest.resetAllMocks();
    expect(fn()).toBeUndefined(); // implementation gone
  });

  test("leaves a spy installed", () => {
    const obj = { greet: (n) => `Hello, ${n}` };
    jest.spyOn(obj, "greet").mockReturnValue("mocked");
    jest.resetAllMocks();
    expect(obj.greet("Ana")).toBeUndefined(); // spy still installed
  });
});

// ============================================
// PART 3: restoreAllMocks
// ============================================
describe("restore", () => {
  test("removes the spy", () => {
    const obj = { greet: (n) => `Hello, ${n}` };
    jest.spyOn(obj, "greet").mockReturnValue("mocked");
    jest.restoreAllMocks();
    expect(obj.greet("Ana")).toBe("Hello, Ana"); // original restored
  });
});

// ============================================
// PART 4: THE CONFIG
// ============================================
// jest.config.js
// module.exports = {
//   clearMocks: true,
//   restoreMocks: true,
// };

The parts covered clearAllMocks, resetAllMocks (including the spy behavior), restoreAllMocks, and the config.


Quick Reference

The Three Functions

FunctionClears HistoryClears ImplementationRestores Spy
clearAllMocks()YesNoNo
resetAllMocks()YesYesNo (spy installed)
restoreAllMocks()YesYesYes

The Config Options

OptionCallsEffect
clearMocksclearAllMocks()History only
resetMocksresetAllMocks()History + implementation
restoreMocksrestoreAllMocks()Restore spies

Jest vs Vitest

BehaviorJestVitest
resetAllMocks on spyLeaves spy returning undefinedRestores original
restoreAllMocksRemoves spyRemoves spy

Best Practices

โœ… Do This:

// Use clearAllMocks when the implementation is shared
const fn = jest.fn().mockReturnValue(42);
jest.clearAllMocks();                                         // โœ…

// Use restoreAllMocks for spies
jest.restoreAllMocks();                                       // โœ…

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

โŒ Don’t Do This:

// Use resetAllMocks expecting the spy to be removed
jest.resetAllMocks(); // spy still installed                  // โŒ

// Use clearAllMocks on a spy that should be restored
jest.clearAllMocks(); // original not restored                // โŒ

// Assume Vitest's mockReset behavior in Jest
// (Jest leaves the spy returning undefined)                  // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Mock still installedresetAllMocks usedUse restoreAllMocks()
Implementation goneresetAllMocks usedUse clearAllMocks()
Jest behaves differently from VitestresetAllMocks on spyCheck the runner
Spy leaks between testsNo restorerestoreMocks: true

Real-World Examples

1. clearAllMocks

jest.clearAllMocks();

2. resetAllMocks

jest.resetAllMocks();

3. restoreAllMocks

jest.restoreAllMocks();

4. clearMocks config

module.exports = { clearMocks: true };

5. resetMocks config

module.exports = { resetMocks: true };

6. restoreMocks config

module.exports = { restoreMocks: true };

7. Per-mock mockClear

fn.mockClear();

8. Per-mock mockReset

fn.mockReset();

9. Per-mock mockRestore

spy.mockRestore();

10. Explicit cleanup in afterEach

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

Visual

Clear vs Reset vs Restore

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const fn = jest.fn().mockReturnValue(42);              โ”‚
โ”‚  fn();                                                  โ”‚
โ”‚                                                         โ”‚
โ”‚  clearAllMocks()                                        โ”‚
โ”‚    calls: []        return: 42                          โ”‚
โ”‚                                                         โ”‚
โ”‚  resetAllMocks()                                        โ”‚
โ”‚    calls: []        return: undefined                   โ”‚
โ”‚                                                         โ”‚
โ”‚  restoreAllMocks()                                      โ”‚
โ”‚    calls: []        spy removed                         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Spy Behavior

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  JEST                           VITEST                  โ”‚
โ”‚                                                         โ”‚
โ”‚  resetAllMocks()                mockReset()             โ”‚
โ”‚    โ†’ returns undefined            โ†’ original restored   โ”‚
โ”‚    โ†’ spy still installed          โ†’ spy still installed โ”‚
โ”‚                                                         โ”‚
โ”‚  restoreAllMocks()              mockRestore()           โ”‚
โ”‚    โ†’ spy removed                  โ†’ spy removed         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Config Mapping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  clearMocks: true    โ†’ jest.clearAllMocks()             โ”‚
โ”‚  resetMocks: true    โ†’ jest.resetAllMocks()             โ”‚
โ”‚  restoreMocks: true  โ†’ jest.restoreAllMocks()           โ”‚
โ”‚                                                         โ”‚
โ”‚  All run before each test.                              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Clear historyclearAllMocks()
Clear history + implementationresetAllMocks()
Restore spiesrestoreAllMocks()
Jest spy resetReturns undefined
Vitest spy resetRestores original
Config optionsclearMocks, resetMocks, restoreMocks

Key takeaways:

  • clearAllMocks clears only the history. The implementation survives, so a mock that returns 42 still returns 42. It is the lightest reset and the correct choice for a mock configured at module scope.
  • resetAllMocks clears the history and the implementation. On a standalone mock, the next call returns undefined. On a spy, Jest leaves the spy installed and returning undefined, which is the behavior that differs from Vitest.
  • restoreAllMocks removes the spy. The object’s method is the original function again, and the spy is no longer installed. It is the correct choice when the test needs the real method back.
  • The three config options automate the three functions. clearMocks calls clearAllMocks, resetMocks calls resetAllMocks, and restoreMocks calls restoreAllMocks before each test.
  • Jest’s resetAllMocks on a spy is not Vitest’s. A test that migrates from Vitest and relies on mockReset restoring the original will behave differently in Jest, because the spy remains installed and returns undefined.

Remember: The three cleanup functions differ in what they clear and whether the spy survives. clearAllMocks keeps the implementation, resetAllMocks removes it, and restoreAllMocks removes the spy. In Jest, resetAllMocks on a spy leaves it installed and returning undefined, which is the detail that makes a migrated test behave differently. Use clearAllMocks for the shared implementation, resetAllMocks for the per-test implementation, and restoreAllMocks for the spy that must not leak.

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!