Jest mocking default exports - require vs import
Solution 1:
You can use either es6 import
or require js
to import your js files in your jest tests.
When using es6 import
you should know that jest is trying to resolve all the dependencies and also calls the constructor for the class that you are importing. During this step, you cannot mock it. The dependency has to be successfully resolved, and then you can proceed with mocks.
I should also add that as can be seen here jest by default hoists any jest.mocks to the top of the file so the order in which you place your imports does not really matter.
Your problem though is different. Your mock function assumes that you have included your js file using require js
.
jest.mock('./dependecy', () => {
return {
default: jest.fn()
};
});
When you import a file using require js
, this is the structure it has:
So assuming I have imported my class called "Test" using require js
, and it has method called "doSomething" I could call it in my test by doing something like:
const test = require('../Test');
test.default.doSomething();
When importing it using es6 import
, you should do it differently though. Using the same example:
import Test from '../Test';
Test.doSomething();
EDIT: If you want to use es6 import
change your mock function to:
jest.mock('./dependecy', () => jest.fn());
Solution 2:
Have you tried something like this? I was dealing with the default export mocking for months until I found this.
jest.mock('./dependency', () => () => jest.fn());
The idea behind this line is that you are exporting a module that is a function. So you need to let Jest knows that it has to mock all your ./dependency
file as a function, that returns a jest.fn()