1

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.

1 Answer 1

1

It is not cached as you assume. The statement you show that uses f() is a top-level statement and therefore it only runs once when the module is first imported. It doesn't matter how many times you expect a to equal 1, you're not re-executing any code whatsoever. The only time that the code in the ./asd module ran was when the module was first imported, when zero test cases had been executed.

This is just how ES modules work: Top-level statements run when the module is first imported, and don't run anymore.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.