Skip to content
jshacks.dev
Testing

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.

1 min read
Summarize in AI

Leftover calls and implementations make tests depend on their order. Three config options clean mocks before each test, and each does a different amount.

vitest.config.jsJavaScript
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    clearMocks: true,
    mockReset: false,
    restoreMocks: true,
  },
});
counter.test.jsJavaScript
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);
});
Text
 ✓ 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.

Taggedvitest
Share

More snippets

Debugging

Debug a single Vitest test in VS Code

Run one Vitest file under the VS Code debugger with a launch configuration that passes the open file, so breakpoints in tests and source work. Vitest 3.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.