Vitest 12 🧪 Mock Reset Semantics — mockReset vs mockClear vs restoreAllMocks
Vitest has three mock reset methods and three config options that call them automatically, and the difference between them is what they clear. mockClear() clears the call history but keeps the implementation. mockReset() clears the call history and the implementation, and for a mock created with vi.spyOn() it also restores the original method. mockRestore() restores the original method for a spy and removes the mock. The names are close enough that a test can pass with the wrong one and fail with the right one, so the distinction is worth stating precisely.
This chapter covers the three methods, the config options that call them, and the spy versus standalone mock difference that determines whether mockReset 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: mockClear clears the history, mockReset clears the history and the implementation, and mockRestore restores the original for a vi.spyOn() mock; in Vitest, mockReset on a spy also restores the original, which is the behavior that differs from Jest.
a. mockClear and the call history
mockClear() resets the mock’s call history: 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.
import { vi, expect, test } from "vitest";
const fn = vi.fn().mockReturnValue(42);
fn();
expect(fn).toHaveBeenCalledTimes(1);
fn.mockClear();
expect(fn).not.toHaveBeenCalled(); // history cleared
expect(fn()).toBe(42); // implementation kept
The mockClear() 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 vi.clearAllMocks() before each test, which applies mockClear() to every mock in the file. It is the setting for a suite where the mocks are configured once and only the call history needs to be reset.
// vitest.config.ts
export default defineConfig({
test: {
clearMocks: true,
},
});
b. mockReset and the implementation
mockReset() clears the call history and the implementation. A mock that returned 42 returns undefined after the reset, and a spy that called the original method no longer calls it.
const fn = vi.fn().mockReturnValue(42);
fn();
fn.mockReset();
expect(fn).not.toHaveBeenCalled(); // history cleared
expect(fn()).toBeUndefined(); // implementation cleared
The Vitest-specific detail is the behavior on a spy. In Vitest, mockReset() on a mock created with vi.spyOn() also restores the original method. The mock is left installed, but it calls the original implementation again.
const obj = { greet: (name: string) => `Hello, ${name}` };
const spy = vi.spyOn(obj, "greet").mockReturnValue("mocked");
expect(obj.greet("Ana")).toBe("mocked");
spy.mockReset();
expect(obj.greet("Ana")).toBe("Hello, Ana"); // original restored
This is the behavior that differs from Jest. In Jest, mockReset() clears the implementation but leaves the spy in place, so obj.greet() returns undefined until the test configures it again. In Vitest, the reset restores the original, which means the next call goes through the real method.
The resetMocks: true config option calls vi.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. mockRestore and the spy removal
mockRestore() removes the spy and restores the original method. For a mock created with vi.spyOn(), the object’s method is the original function again, and the spy is no longer installed.
const spy = vi.spyOn(obj, "greet").mockReturnValue("mocked");
spy.mockRestore();
expect(obj.greet("Ana")).toBe("Hello, Ana");
expect(obj.greet).not.toBe(spy); // spy removed
The restoreMocks: true config option calls vi.restoreAllMocks() before each test. It is the safest default for a suite that uses vi.spyOn(), because the spy does not leak into the next test regardless of how it was declared.
The difference between mockReset and mockRestore in Vitest is narrower than in Jest. Both restore the original behavior for a spy; mockRestore removes the spy, and mockReset leaves it installed. The practical consequence is that a test that calls mockReset and then asserts on the spy’s call history still sees a spy, while a test that calls mockRestore sees the original method.
The mockRestore() is the correct choice when the test needs the original method back. The mockReset() is the correct choice when the test needs the mock to return to its default behavior but still wants to assert on the next call.
Complete Example Session
// ============================================
// PART 1: mockClear
// ============================================
import { vi, describe, test, expect } from "vitest";
describe("mockClear", () => {
test("keeps the implementation", () => {
const fn = vi.fn().mockReturnValue(42);
fn();
fn.mockClear();
expect(fn).not.toHaveBeenCalled();
expect(fn()).toBe(42); // still returns 42
});
});
// ============================================
// PART 2: mockReset
// ============================================
describe("mockReset", () => {
test("clears the implementation", () => {
const fn = vi.fn().mockReturnValue(42);
fn.mockReset();
expect(fn()).toBeUndefined(); // implementation gone
});
test("restores the original on a spy", () => {
const obj = { greet: (n: string) => `Hello, ${n}` };
const spy = vi.spyOn(obj, "greet").mockReturnValue("mocked");
spy.mockReset();
expect(obj.greet("Ana")).toBe("Hello, Ana"); // original
});
});
// ============================================
// PART 3: mockRestore
// ============================================
describe("mockRestore", () => {
test("removes the spy", () => {
const obj = { greet: (n: string) => `Hello, ${n}` };
const spy = vi.spyOn(obj, "greet").mockReturnValue("mocked");
spy.mockRestore();
expect(obj.greet("Ana")).toBe("Hello, Ana");
expect(obj.greet).not.toBe(spy);
});
});
// ============================================
// PART 4: THE CONFIG
// ============================================
// vitest.config.ts
// test: {
// clearMocks: true, // vi.clearAllMocks() before each test
// restoreMocks: true, // vi.restoreAllMocks() before each test
// }
The parts covered mockClear, mockReset (including the spy behavior), mockRestore, and the config.
Quick Reference
The Three Methods
| Method | Clears History | Clears Implementation | Removes Spy |
|---|---|---|---|
mockClear() | Yes | No | No |
mockReset() | Yes | Yes | No (restores original) |
mockRestore() | Yes | Yes | Yes |
The Config Options
| Option | Calls | Effect |
|---|---|---|
clearMocks | vi.clearAllMocks() | History only |
resetMocks | vi.resetAllMocks() | History + implementation |
restoreMocks | vi.restoreAllMocks() | Restore spies |
Vitest vs Jest
| Behavior | Vitest | Jest |
|---|---|---|
mockReset on spy | Restores original | Leaves spy returning undefined |
mockRestore | Removes spy | Removes spy |
Best Practices
✅ Do This:
// Use mockClear when the implementation is shared
const fn = vi.fn().mockReturnValue(42);
fn.mockClear(); // ✅
// Use mockRestore for spies
spy.mockRestore(); // ✅
// Configure the global restore
test: { restoreMocks: true } // ✅
❌ Don’t Do This:
// Use mockReset expecting the mock to be removed
spy.mockReset(); // spy still installed // ❌
// Use mockClear on a spy that should be restored
spy.mockClear(); // original not restored // ❌
// Assume Jest's mockReset behavior in Vitest
// (Vitest restores the original) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Mock still installed | mockReset used | Use mockRestore() |
| Implementation gone | mockReset used | Use mockClear() |
| Vitest behaves differently from Jest | mockReset on spy restores original | Check the version |
| Spy leaks between tests | No restore | restoreMocks: true |
Real-World Examples
1. mockClear
const fn = vi.fn().mockReturnValue(42);
fn.mockClear();
expect(fn()).toBe(42);
2. mockReset on a standalone mock
const fn = vi.fn().mockReturnValue(42);
fn.mockReset();
expect(fn()).toBeUndefined();
3. mockReset on a spy
const spy = vi.spyOn(obj, "method").mockReturnValue("mocked");
spy.mockReset();
expect(obj.method()).toBe(originalValue);
4. mockRestore
spy.mockRestore();
5. clearMocks config
test: { clearMocks: true }
6. restoreMocks config
test: { restoreMocks: true }
7. resetMocks config
test: { resetMocks: true }
8. Explicit clear in afterEach
afterEach(() => { vi.clearAllMocks(); });
9. Explicit restore in afterEach
afterEach(() => { vi.restoreAllMocks(); });
10. The spy removal check
expect(obj.method).not.toBe(spy);
Visual
Clear vs Reset vs Restore
┌─────────────────────────────────────────────────────────┐
│ const fn = vi.fn().mockReturnValue(42); │
│ fn(); │
│ │
│ mockClear() │
│ calls: [] return: 42 │
│ │
│ mockReset() │
│ calls: [] return: undefined │
│ │
│ mockRestore() │
│ calls: [] spy removed │
└─────────────────────────────────────────────────────────┘
The Spy Behavior
┌─────────────────────────────────────────────────────────┐
│ VITEST JEST │
│ │
│ spy.mockReset() spy.mockReset() │
│ → original restored → returns undefined │
│ → spy still installed → spy still installed│
│ │
│ spy.mockRestore() spy.mockRestore() │
│ → spy removed → spy removed │
└─────────────────────────────────────────────────────────┘
Config Mapping
┌─────────────────────────────────────────────────────────┐
│ clearMocks: true → vi.clearAllMocks() │
│ resetMocks: true → vi.resetAllMocks() │
│ restoreMocks: true → vi.restoreAllMocks() │
│ │
│ All run before each test. │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Clear history | mockClear() |
| Clear history + implementation | mockReset() |
| Remove spy | mockRestore() |
| Vitest spy reset | Restores original |
| Jest spy reset | Returns undefined |
| Config options | clearMocks, resetMocks, restoreMocks |
Key takeaways:
mockClearclears only the history. The implementation survives, so a mock that returns42still returns42. It is the lightest reset and the correct choice for a mock configured at module scope.mockResetclears the history and the implementation. On a standalone mock, the next call returnsundefined. On a spy, Vitest restores the original method, which is the behavior that differs from Jest.mockRestoreremoves 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 methods.
clearMockscallsclearAllMocks,resetMockscallsresetAllMocks, andrestoreMockscallsrestoreAllMocksbefore each test. - Vitest’s
mockReseton a spy is not Jest’s. A test that migrates from Jest and relies onmockResetleaving the spy returningundefinedwill behave differently in Vitest, because the original method is restored.
Remember: The three reset methods differ in what they clear and whether the spy survives. mockClear keeps the implementation, mockReset removes it, and mockRestore removes the spy. In Vitest, mockReset on a spy also restores the original, which is the detail that makes a migrated test behave differently. Use mockClear for the shared implementation, mockReset for the per-test implementation, and mockRestore for the spy that must not leak.
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!