I'm having difficulty mocking a constructor of a class from an imported module. Interestingly, it works perfectly when my mock implementation is directly inserted into the jest.mock() factory function, but fails when the implementation is imported from another file.
Successful Implementation:
test.ts:
jest.mock('external-lib', () => {
const originalModule = jest.requireActual('@external-lib');
function ClassMock(): any {
return {
method1: (val: number): Promise<any> => {
return Promise.resolve({ a: val });
},
};
}
return {
__esModule: true,
...originalModule,
StrategyComputation: jest.fn(ClassMock),
};
});
Unsuccessful Attempt:
When I extract the function ClassMock
into another file mocks.ts
and import it in the test file, it stops working:
test.ts:
import { ClassMock } from './mocks';
jest.mock('external-lib', () => {
const originalModule = jest.requireActual('@external-lib');
return {
__esModule: true,
...originalModule,
StrategyComputation: jest.fn(ClassMock),
};
});
mocks.ts:
export function ClassMock(): any {
return {
method1: (val: number): Promise<any> => {
return Promise.resolve({ a: val });
},
};
}
Unfortunately, it leads to an error:
TypeError: Cannot read property 'ClassMock' of undefined