I'm migrating from Jest to Vitest and struggling to provide a different mock value in each test case.
Basic example:
// test.ts
import { a } from './asd';
const { f } = vi.hoisted(() => {
return {
f: vi.fn(),
};
});
vi.mock('../../../api/ApiProvider', () => ({
f,
}));
describe('Test', () => {
it('sample test case', () => {
f.mockReturnValue(42);
expect(a).toEqual(1);
});
it('sample test case2', () => {
f.mockReturnValue(43);
expect(a).toEqual(1);
});
});
// asd.ts
import { f } from '../../../api/ApiProvider';
console.log('IMPORTING API PROVIDER', f());
export const a = 1;
The issue seems to stem from the fact that when the ApiProvider module is imported, it is cached and uses the initial mocking implementation of vi.mock which is an empty mock function, hence why IMPORTING API PROVIDER returns undefined. The f.mockReturnValue() calls seem to be ignored. I can provide a default implementation in the mock call, but what if I want to change this in another test case? Is there a way to disable the module import caching or am I doing something wrong?
The same code was working when using Jest and mockImplementation calls were applied in the test file.
The setup files do not import any modules so the caching is also not caused by this.