I have a Jest test that I am writing for a function which makes an API call. If the API call returns a 403, a function from a node module should be called. I am trying to test this using a mock jest function, but I cannot get the test to use the mocked version of the module I am making.
file.spec.js
import file from './file'
const mockedNodeModule = jest.genMockFromModule('nodeModule')
mockedNodeModule.namedExport = { logout: jest.fn() }
it('call returns a 403', async () => {
await file.apiCall('brand', 'entityType', 'name')
expect(mockedNodeModule.namedExport.logout).toHaveBeenCalled()
})
file.js
import { namedExport } from './nodeModule';
import api from './api';
const apiCall = () => {
return api.makeCall().then(
() => {},
(error) => {
if (error.status === 403) {
namedExport.logout();
}
},
);
};
export default { apiCall };
The test always fails when I check whether mockedNodeModule.namedExport.logout has been called. When I put a breakpoint on the line that it is called, it seems that the mocked version is not being used when the test is running (i.e. it is still using the module from my node_modules). I have also tried using jest.mock() as well, but the result is the same. Is there something wrong in the way that I am setting up the test? Can jest not mock node modules in cases like this?