Course contentsShow
← React
Lesson 2082 of 2,39646. Testing React with RTLFree lesson

Resetting and Restoring Mocks

Managing mock state between tests with mockClear, mockReset, mockRestore, and restoreAllMocks.

Resetting and Restoring Mocks

You'll learn how to properly clean up mock state between tests to prevent unexpected interactions and test pollution.

The Problem: Stateful Mocks

When you create mocks with vi.mock() or vi.spyOn(), they accumulate call history and retain their mock implementations across tests. Without cleanup, one test's mock behavior can leak into another, causing false positives or mysterious failures. It's like using the same notebook for multiple exams without erasing previous answers.

The Cleanup Methods

mockClear()

Resets call history (how many times called, with what arguments) but keeps the mock implementation intact. Use this when you want to verify calls in isolation while keeping the same fake behavior.

const mockFn = vi.fn(() => 'mocked');
mockFn('test');
expect(mockFn).toHaveBeenCalledTimes(1);

mockFn.mockClear();
expect(mockFn).toHaveBeenCalledTimes(0); // Call history cleared
mockFn(); // Still returns 'mocked'

mockReset()

Does everything mockClear() does plus removes the mock implementation. The function becomes a no-op returning undefined.

mockFn.mockReset();
expect(mockFn()).toBeUndefined(); // Implementation gone

mockRestore()

Only works with vi.spyOn(). Restores the original implementation completely, as if you never spied at all.

const original = obj.method;
vi.spyOn(obj, 'method');
obj.method.mockRestore();
// obj.method === original again

restoreAllMocks()

Global cleanup that calls mockRestore() on all spies. Typically placed in afterEach() hooks for automatic cleanup.

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

Key Takeaway: Use mockClear() to reset call counts, mockReset() to fully clear mocks, mockRestore() to undo spies, and restoreAllMocks() in cleanup hooks to prevent test pollution.