If you are writing tests using Jest and you use TypeScript, there is a good chance you have encountered an error along the lines of TypeError: defaultsDeep_1.default is not a function
or TypeError: myClass.default is not a constructor
when trying to test a file that is using a default import from a module.
You most likely have read countless StackOverflow questions, but none of the solutions will solve the issue. You’ve read the Jest documentation (which is quite extensive), but still no mention of mocking default module imports with TypeScript.
In my case, I had this error when trying to import a Lodash function defaultsDeep
and another when importing the Input Mask module. My imports look like the following.
import defaultsDeep from 'lodash/defaultsDeep';
import Inputmask, { Options, Instance } from 'inputmask';
Inside of my test which will be testing this specific file, I use jest.mock
to mock the specific modules and their implementations. The important thing to note here is I am returning default
from within my mocks. This is because of how default imports are transpiled within TypeScript.
The Lodash mock is more simplistic:
jest.mock('lodash/defaultsDeep', () => {
return {
default: jest.fn()
};
In the case of Input Mask, I needed to mock an instance which has a method on it. The usage in the actual file highlights what we want to achieve. The input mask plugin is newable, it then exposes a mask
method which we supply with an element.
this.im = new Inputmask(options);
this.im.mask(element);
This is how we mock the above module and accommodate for the usage:
jest.mock('inputmask', () => {
return {
default: jest.fn().mockImplementation(() => {
return {
mask: jest.fn()
};
})
};
});
The convenient thing about the solutions presented is they will work for all default imported modules. Have fun.
With jest v26, I had to use `{ __esModule: true, default: jest.fn() }` in order for it to work. Hope it helps! 😀