When using Vitest mocking, avoid multiple `vi.mock` calls for the same module within a single test file, as mock calls are hoisted and can interfere with each other. Instead, organize tests requiring different mock configurations into separate test files or test suites with proper setup/teardown.
When using Vitest mocking, avoid multiple vi.mock
calls for the same module within a single test file, as mock calls are hoisted and can interfere with each other. Instead, organize tests requiring different mock configurations into separate test files or test suites with proper setup/teardown.
The issue arises because vi.mock
calls are hoisted to the top of the file, making it impossible to have different mock implementations for different test scenarios in the same file. This can cause tests to break unexpectedly when mock configurations conflict.
Problematic approach:
// This won't work as expected - both mocks target the same module
vi.mock("../../../context/ExtensionStateContext", () => ({
useExtensionState: vi.fn(() => ({ apiProvider: "openai" }))
}))
vi.mock("../../../context/ExtensionStateContext", () => ({
useExtensionState: vi.fn(() => ({ apiProvider: "nebius" }))
}))
Better approach:
beforeEach
/afterEach
to modify mock return values within the same mock setupThis ensures test isolation and prevents one test’s mock configuration from breaking others.
Enter the URL of a public GitHub repository