From b62516fc679aaaacb388b774d69138a536681371 Mon Sep 17 00:00:00 2001 From: Johan Gorter Date: Tue, 8 Sep 2026 13:49:42 +0200 Subject: [PATCH 1/2] perf(spy): reset only mocks that were called or reconfigured Co-Authored-By: Claude Fable 5.1 --- packages/spy/src/index.ts | 30 ++++++++++++------------ test/unit/test/mocking/vi-fn.test.ts | 35 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/packages/spy/src/index.ts b/packages/spy/src/index.ts index 972cd7b66168..017629717805 100644 --- a/packages/spy/src/index.ts +++ b/packages/spy/src/index.ts @@ -25,10 +25,9 @@ const MOCK_RESTORE = new Set<() => void>() // but it makes the state slower to access and return different values // if you stored it before calling `mockClear` where it will be recreated const DIRTY_MOCK_STATES = new Set>() -const REGISTERED_MOCKS = new Set>>() -const MOCK_FINALIZER = new FinalizationRegistry>>((ref) => { - REGISTERED_MOCKS.delete(ref) -}) +// Mocks whose implementation, once-queue or name changed since their last +// `mockReset()`, so `resetAllMocks()` only visits mocks that are not already reset +const DIRTY_MOCK_CONFIGS = new Set>() const MOCK_CONFIGS = new WeakMap, MockConfig>() const MOCKS_BY_STATE = new WeakMap>() @@ -68,9 +67,6 @@ export function createMockInstance(options: MockInstanceOption = {}): Mock { @@ -102,18 +98,21 @@ export function createMockInstance(options: MockInstanceOption = {}): Mock { expect(mock()).toBe(undefined) }) + test('vi.resetAllMocks() only resets mocks that were called or reconfigured', () => { + const mocks = Array.from({ length: 100 }, () => vi.fn()) + mocks[10]() + mocks[20].mockReturnValue(42) + mocks[30].mockReturnValueOnce(42) + mocks[40].mockName('named') + mocks[50]() + mocks[50].mockReturnValue(42) + + const reset: number[] = [] + for (const [index, mock] of mocks.entries()) { + const mockReset = mock.mockReset + mock.mockReset = function () { + reset.push(index) + return mockReset.call(this) + } + } + + vi.resetAllMocks() + + expect(reset.sort((a, b) => a - b)).toEqual([10, 20, 30, 40, 50]) + expect(mocks[20]()).toBe(undefined) + expect(mocks[30]()).toBe(undefined) + expect(mocks[40].getMockName()).toBe('vi.fn()') + }) + + test('vi.resetAllMocks() still resets a reconfigured mock after vi.clearAllMocks()', () => { + const mock = vi.fn().mockReturnValue(42) + + vi.clearAllMocks() + vi.resetAllMocks() + + expect(mock()).toBe(undefined) + }) + test('vi.fn() resets the original mock implementation', () => { const mock = vi.fn(() => 42) expect(mock()).toBe(42) From 26dbc14564d87fcdc8876ec7149d1d848d8feb4e Mon Sep 17 00:00:00 2001 From: Johan Gorter Date: Tue, 15 Sep 2026 10:11:12 +0200 Subject: [PATCH 2/2] perf(spy): track dirty mocks with weak refs Co-Authored-By: Claude Fable 5.1 --- packages/spy/src/index.ts | 68 +++++++++++++------ .../unit/test/mocking/vi-fn-retention.test.ts | 48 +++++++++++++ test/unit/test/mocking/vi-fn.test.ts | 23 +++++++ 3 files changed, 120 insertions(+), 19 deletions(-) create mode 100644 test/unit/test/mocking/vi-fn-retention.test.ts diff --git a/packages/spy/src/index.ts b/packages/spy/src/index.ts index 017629717805..d389d715edca 100644 --- a/packages/spy/src/index.ts +++ b/packages/spy/src/index.ts @@ -21,16 +21,51 @@ export function isMockFunction(fn: any): fn is Mock { } const MOCK_RESTORE = new Set<() => void>() +type MockRef = WeakRef> // Jest keeps the state in a separate WeakMap which is good for memory, // but it makes the state slower to access and return different values // if you stored it before calling `mockClear` where it will be recreated -const DIRTY_MOCK_STATES = new Set>() +const DIRTY_MOCK_STATES = new Set() // Mocks whose implementation, once-queue or name changed since their last // `mockReset()`, so `resetAllMocks()` only visits mocks that are not already reset -const DIRTY_MOCK_CONFIGS = new Set>() +const DIRTY_MOCK_CONFIGS = new Set() +const MOCK_REFS = new WeakMap, MockRef>() +const MOCK_FINALIZER = new FinalizationRegistry((ref) => { + DIRTY_MOCK_STATES.delete(ref) + DIRTY_MOCK_CONFIGS.delete(ref) +}) const MOCK_CONFIGS = new WeakMap, MockConfig>() const MOCKS_BY_STATE = new WeakMap>() +function markDirty(set: Set, mock: Mock): void { + let ref = MOCK_REFS.get(mock) + if (!ref) { + ref = new WeakRef(mock) + MOCK_REFS.set(mock, ref) + MOCK_FINALIZER.register(mock, ref) + } + set.add(ref) +} + +function unmarkDirty(set: Set, mock: Mock): void { + const ref = MOCK_REFS.get(mock) + if (ref) { + set.delete(ref) + } +} + +function forEachDirty(set: Set, fn: (mock: Mock) => void): void { + for (const ref of set) { + const mock = ref.deref() + if (mock) { + fn(mock) + } + else { + set.delete(ref) + } + } +} + export function createMockInstance(options: MockInstanceOption = {}): Mock { const { originalImplementation, @@ -98,27 +133,28 @@ export function createMockInstance(options: MockInstanceOption = {}): Mock { config.mockImplementation = previousImplementation config.onceMockImplementations = previousOnceImplementations + markDirty(DIRTY_MOCK_CONFIGS, mock) updateMockPrototype() } @@ -227,7 +263,7 @@ export function createMockInstance(options: MockInstanceOption = {}): Mock> = { // to keep the name of the function intact [name]: (function (this: any, ...args: any[]) { - DIRTY_MOCK_STATES.add(namedObject[name]) + markDirty(DIRTY_MOCK_STATES, namedObject[name]) if (prototypeMock) { - DIRTY_MOCK_STATES.add(prototypeMock) + markDirty(DIRTY_MOCK_STATES, prototypeMock) } registerCalls(args, state, prototypeState) registerInvocationOrder(invocationCallCounter++, state, prototypeState) @@ -772,20 +808,14 @@ export function restoreAllMocks(): void { } export function clearAllMocks(): void { - for (const mock of DIRTY_MOCK_STATES) { - mock.mockClear() - } + forEachDirty(DIRTY_MOCK_STATES, mock => mock.mockClear()) } export function resetAllMocks(): void { // `mockReset()` removes the mock from both sets, so a mock present in both // is visited once. - for (const mock of DIRTY_MOCK_STATES) { - mock.mockReset() - } - for (const mock of DIRTY_MOCK_CONFIGS) { - mock.mockReset() - } + forEachDirty(DIRTY_MOCK_STATES, mock => mock.mockReset()) + forEachDirty(DIRTY_MOCK_CONFIGS, mock => mock.mockReset()) } function throwConstructorError(shorthand: string): never { diff --git a/test/unit/test/mocking/vi-fn-retention.test.ts b/test/unit/test/mocking/vi-fn-retention.test.ts new file mode 100644 index 000000000000..8cc168ef1ebe --- /dev/null +++ b/test/unit/test/mocking/vi-fn-retention.test.ts @@ -0,0 +1,48 @@ +import type { Mock } from 'vitest' +import v8 from 'node:v8' +import vm from 'node:vm' +import { expect, test, vi } from 'vitest' + +// node exposes no public gc hook, but the flag can be flipped just long +// enough to grab one from a throwaway context +v8.setFlagsFromString('--expose-gc') +const gc = vm.runInNewContext('gc') +v8.setFlagsFromString('--no-expose-gc') + +type Fn = Mock<() => unknown> + +function createMocks(create: () => Fn, use: (mock: Fn) => void): WeakRef[] { + return Array.from({ length: 100 }, () => { + const mock = create() + use(mock) + return new WeakRef(mock) + }) +} + +async function countAlive(refs: WeakRef[]): Promise { + let alive = refs.length + for (let attempt = 0; attempt < 10 && alive > 0; attempt++) { + await new Promise(resolve => setTimeout(resolve, 10)) + gc() + alive = refs.filter(ref => ref.deref()).length + } + return alive +} + +function noop() {} + +test.each([ + ['called, nothing clears them', () => vi.fn(), (mock: Fn) => mock(), noop], + ['configured, nothing clears them', () => vi.fn(), (mock: Fn) => mock.mockReturnValue(1), noop], + ['created with an implementation, only vi.clearAllMocks() runs', () => vi.fn(() => 1), noop, () => vi.clearAllMocks()], + ['configured, only vi.clearAllMocks() runs', () => vi.fn(), (mock: Fn) => mock.mockReturnValue(1), () => vi.clearAllMocks()], + ['called and configured, only vi.clearAllMocks() runs', () => vi.fn(), (mock: Fn) => { + mock.mockReturnValue(1) + mock() + }, () => vi.clearAllMocks()], +])('unreferenced mocks are collected: %s', async (_, create, use, cleanup) => { + const refs = createMocks(create, use) + cleanup() + + expect(await countAlive(refs)).toBe(0) +}) diff --git a/test/unit/test/mocking/vi-fn.test.ts b/test/unit/test/mocking/vi-fn.test.ts index 7fc0f9c4b4e8..0c193fde4d73 100644 --- a/test/unit/test/mocking/vi-fn.test.ts +++ b/test/unit/test/mocking/vi-fn.test.ts @@ -380,6 +380,29 @@ describe('vi.fn() configuration', () => { expect(mock()).toBe(undefined) }) + test('vi.resetAllMocks() resets an implementation restored by withImplementation after mockReset()', () => { + const mock = vi.fn().mockImplementation(() => 1) + mock.withImplementation(() => 2, () => { + mock.mockReset() + }) + expect(mock.getMockImplementation()?.()).toBe(1) + + vi.resetAllMocks() + + expect(mock.getMockImplementation()).toBe(undefined) + }) + + test('vi.resetAllMocks() resets a once implementation restored by withImplementation after mockReset()', () => { + const mock = vi.fn().mockImplementationOnce(() => 1) + mock.withImplementation(() => 2, () => { + mock.mockReset() + }) + + vi.resetAllMocks() + + expect(mock.getMockImplementation()).toBe(undefined) + }) + test('vi.fn() resets the original mock implementation', () => { const mock = vi.fn(() => 42) expect(mock()).toBe(42)