Course contentsShow
← JavaScript
Lesson 2705 of 2,72354. Testing in JavaScriptFree lesson

Clearing and Resetting Mocks

Use mockClear, mockReset, and mockRestore to manage mock state between tests.

Clearing and Resetting Mocks

You'll learn how to clean up mock state between tests to prevent test pollution and ensure isolation.

Why Mock Cleanup Matters

When you use jest.fn() or jest.spyOn(), Jest tracks every call—arguments, return values, everything. Without cleanup, data from one test bleeds into the next, causing confusing failures. Think of it like washing dishes: if you don't clean between meals, yesterday's leftovers contaminate today's food.

Three Cleanup Methods

mockClear() wipes call history (how many times called, with what arguments) but keeps the mock implementation intact. Use this when you want to reset statistics but keep the same behavior.

const mockFn = jest.fn(() => 'hello');

mockFn('first call');
expect(mockFn).toHaveBeenCalledTimes(1);

mockFn.mockClear();
expect(mockFn).toHaveBeenCalledTimes(0); // History cleared
expect(mockFn()).toBe('hello'); // Implementation remains

mockReset() does everything mockClear() does, plus removes the mock implementation and any configured return values. The mock becomes an empty function returning undefined.

const mockFn = jest.fn(() => 'hello');
mockFn();

mockFn.mockReset();
expect(mockFn).toHaveBeenCalledTimes(0); // History cleared
expect(mockFn()).toBeUndefined(); // Implementation gone

mockRestore() only works with jest.spyOn(). It removes the spy entirely and restores the original function.

const obj = { method: () => 'original' };
const spy = jest.spyOn(obj, 'method');
spy.mockImplementation(() => 'mocked');

spy.mockRestore();
expect(obj.method()).toBe('original'); // Original restored

Automation with beforeEach

Apply cleanup automatically using beforeEach():

beforeEach(() => {
  mockFn.mockClear(); // or mockReset()
});

Key Takeaway: Use mockClear() to reset call counts, mockReset() to also remove implementations, and mockRestore() to restore spied functions—ensuring each test starts with a clean slate.