So I have been struggling with how to test dynamic imports generally and in this case, especially in jest, I have been reading a lot on the internet but did not find anything concrete, so I thought about bringing the question up to centralize a decent solution.
I have the following methods inside of a class
class MyClass {
successMethod() { ... }
errorMethod() { ... }
myMethod() {
return import('./myFile.js')
.then(() => this.successMethod())
.catch(() => this.errorMethod());
}
}
My question is:
How do you mock both Success and Failing promise cases for this dynamic import using Jest to make sure each method (successMethod
and errorMethod
) are called when resolving or failing respectively?.
I found jest.doMock
helps for mocking the resolved case but did not find a way to make the dynamic import fail by mocking it so the catch
case is uncovered.
Note: this is not a react application, this is a Vanilla JS project.
jest.mock('./myFile.js', () => Promise.reject(new Error('Forcing async import error')));
? – Bowmandefault
export being promise object. – Haleakaladefault
export. It will triggerthen
callback and notcatch
, becauseimport
returns a promise of ES module export object, which in this case is{ default: Promise.reject(...) }
. – Haleakala