I’m trying to migrate a project from Jest to Vitest and I’m having issues with mocks. I can’t figure out why, when mocking a third party module and using mock implementations/mock returned values, these do work inside the test file, but not inside the tested file (where I want the mocked values to actually return). This works without issues with Jest but not with Vitest. Here’s some of the code I have currently:
import internalService from '@internal/js-service'
import idUtil from '@internal/js-service/lib/idUtil'
vi.mock('@internal/js-service', () => {
return {
default: {
init: vi.fn().mockReturnValue('1),
identify: vi.fn(),
},
}
})
vi.mock('@internal/js-service/lib/idUtil', () => ({
default: vi.fn().mockReturnValue('123'),
}))
test('should initialize the internal service with the expected params', () => {
console.log('test', internalService.init(), idUtil())
initializeInternalService({email: '[email protected]'})
expect(internalService.init).toHaveBeenCalledTimes(1)
expect(internalService.init).toHaveBeenCalledWith(
{
email: '[email protected]',
unique_id: '1',
},
)
})
and the tested file:
import internalService from '@internal/js-service'
import idUtil from '@internal/js-service/lib/idUtil'
export const initializeInternalService = (user: User) => {
internalService.init(
{
unique_id: idUtil(),
email: user.email,
},
)
}
When the console.log
runs inside the test, the code returns the mocked values ('1'
and '123'
) as expected, but when running the code in the tested file it seems like the original implementations are run, not the mocked ones, and I don’t understand why.