CodePark/ questions / Mocks, spies & timers
START PRACTICINGPRACTICE
Frontend question · Testing › Mocks, spies & timers

This Jest test fails with 'The module factory of jest.mock() is not allowed to reference any out-of-scope variables'. Why?

import { fetchUser } from "./api";

const fakeUser = { name: "Ana" };

jest.mock("./api", () => ({
  fetchUser: jest.fn(() => Promise.resolve(fakeUser)),
}));
jest.mock is hoisted above the imports and variables, so the factory may only reference outer variables whose names start with mock

jest.mock is hoisted. This means babel-jest moves jest.mock calls to the top of the file, above the imports. Then the mock exists before the import runs. But outer variables may not be initialised yet at that point. So Jest rejects them, unless their names start with mock, like mockUser. A cleaner fix: call jest.mock('./api'), then jest.mocked(fetchUser).mockResolvedValue(...) inside the test. Vitest hoists vi.mock the same way and offers vi.hoisted. The option saying jest.mock must be inside a test block is wrong. It belongs at the top level.