[READ-ONLY] Mirror of https://github.com/vitest-dev/vitest. Next generation testing framework powered by Vite. vitest.dev
vitest docs guide recipes explicit-resources.md
3.6 kB 105 lines
Markdown
at main

--- title: Auto-Cleanup with `using` | Recipes --- # Auto-Cleanup with `using` Spies and mocks need to be restored after the test that installed them, otherwise state leaks between tests. The usual approaches are an `afterEach(() => vi.restoreAllMocks())` at the suite level or a per-test [`onTestFinished(() => spy.mockRestore())`](/api/hooks#ontestfinished) inline. If your runtime supports [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management) (Node.js 24+, or via TypeScript 5.2+ in modern bundlers), there's a tighter option: declare the spy with `using` instead of `const`, and restoration happens automatically when the block exits. This works for [`vi.spyOn`](/api/vi#vi-spyon), [`vi.fn`](/api/vi#vi-fn), and [`vi.doMock`](/api/vi#vi-domock). <Version>3.2.0</Version> ## Pattern ```ts import { expect, it, vi } from 'vitest' function debug(message: string) { console.log(message) } it('calls console.log', () => { using spy = vi.spyOn(console, 'log').mockImplementation(() => {}) debug('message') expect(spy).toHaveBeenCalled() }) // console.log is restored here without an afterEach ``` The same pattern works with `vi.doMock`, which returns a disposable that queues an unmock when the scope exits: ```ts import { expect, it, vi } from 'vitest' it('uses the mocked module, then the real one', async () => { { using _mock = vi.doMock('./users', () => ({ loadUser: () => ({ id: '1', name: 'Alice' }), })) const { loadUser } = await import('./users') expect(loadUser('alice').name).toBe('Alice') } // ./users is unmocked from here on }) ``` ## Scoped to any block `using` is block-scoped, so you can install a spy for just part of a test. This is the case neither `afterEach` nor `onTestFinished` covers, since both run after the test ends: ```ts import { expect, it, vi } from 'vitest' it('only mocks fetch for the auth call', async () => { // real fetch here await preloadConfig() { using fetchSpy = vi.spyOn(globalThis, 'fetch') …