I have to test a Singleton but in his constructor i called a external method. How can i mock it ?
import externalLib from 'externalModule';
class MySingleton {
public static _instance: MySingleton;
private constructor {
externalLib.method() // I have to mock externalLib
}
public static getInstance() {
if (_instance) {
return _instance;
}
return new MySingleton();
}
}
export default MySingleton.getInstance();
Thank you.
You can do it that way (doc https://jestjs.io/docs/en/mock-functions#mocking-modules)
import extLib from 'extLib';
jest.mock('extLib');
test('should fetch users', () => {
extLib.method.mockResolvedValue(MyReturnValue);
// or you could use the following depending on your use case:
// extLib.method.mockImplementation(() => Promise.resolve(MyReturnValue))
// Your testing code here...
});