How to test dynamic imports (then and catch) with Jest
Prototype methods can be spied or mocked on either MyClass.prototype
or class instance. Module mocks and spy functions should be restored for each test in order for them to not affect each other.
let myClass;
beforeEach(() => {
jest.resetModules();
jest.restoreAllMocks();
myClass = new MyClass();
jest.spyOn(myClass, 'successMethod');
jest.spyOn(myClass, 'errorMethod');
});
jest.doMock
requires to import all affected modules after it was called. In order for dynamic import
to result in rejected promise, myFile
module should throw an error when evaluated. Since dynamic import
returns a promise, tests should be asynchronous.
it('...', async () => {
jest.mock('./myFile.js', () => 'value');
await expect(myClass.myMethod()).resolves.toEqual(/* return value from successMethod */);
expect(myClass.successMethod).toBeCalled();
expect(myClass.errorMethod).not.toBeCalled();
});
it('...', async () => {
jest.mock('./myFile.js', () => { throw new Error() });
await expect(myClass.myMethod()).rejects.toThrow(/* error message from errorMethod */);
expect(myClass.successMethod).not.toBeCalled();
expect(myClass.errorMethod).toBeCalled();
});