Reset mocks between tests with restoreMocks
Clear, reset or restore mocks automatically between Vitest tests with clearMocks, mockReset and restoreMocks in the config, and know what each does.
Leftover calls and implementations make tests depend on their order. Three config options clean mocks before each test, and each does a different amount.
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
clearMocks: true,
mockReset: false,
restoreMocks: true,
},
});import { test, expect, vi } from 'vitest';
const handler = vi.fn(() => 'real');
test('first call is recorded', () => {
handler();
expect(handler).toHaveBeenCalledTimes(1);
});
test('starts with no calls', () => {
expect(handler).toHaveBeenCalledTimes(0);
}); ✓ counter.test.js (2 tests)
Test Files 1 passed (1)
Tests 2 passed (2)clearMocks runs mockClear() before each test, which empties mock.calls and results but keeps the implementation. That is why the second test sees zero calls. mockReset also resets the implementation to the original one that was passed to vi.fn(impl). restoreMocks puts back the original methods of spies made with vi.spyOn. These are the Vitest 3 and later meanings. See the config options.
Older Vitest versions made mockReset return undefined, so check the release notes when upgrading. Clearing is the safest default. Reset only if tests should not inherit an implementation, and remember that mocks created inside beforeEach are fresh anyway.