I have seen questions referring to the mocking of default exports with jest around here, but I don't think this has already been asked:
When mocking the default export of a dependency of a module that is being tested, the tests suite fails to run if the module imports the dependency with the ES6 import statement, stating TypeError: (0 , _dependency.default) is not a function
It succeeds, however, if the module uses a require().default
call instead.
In my understanding, import module from location
directly translates to const module = require(location).default
, so I am very confused why this is happening. I'd rather keep my code style consistent and not use the require
call in the original module.
Is there a way to do it?
Test file with mock:
import './modules.js';
import dependency from './dependency';
jest.mock('./dependency', () => {
return {
default: jest.fn()
};
});
// This is what I would eventually like to call
it('calls the mocked function', () => {
expect(dependency).toHaveBeenCalled();
});
Dependency.js
export default () => console.log('do something');
module.js (not working)
import dependency from './dependency.js';
dependency();
module.js (working)
const dependency = require('./dependency.js').default;
dependency();
dependency
call happening on a different module from thejest.mock
call? – Plathjest.mock('./dependecy', () => jest.fn());
work in both cases? – Rostand