In testing ES6 modules, the need often arises to mock imported modules to isolate and assert on specific functionality. In this context, Jest provides several options for mocking module imports.
The traditional approach involves mocking individual named exports or default exports using jest.mock or jest.spyOn, respectively. However, for more complex scenarios, a more flexible method exists.
Utilizing import * allows the mocking of all exports from a module, including both named and default exports. Here's the modified code using this approach:
<code class="js">// dependency.js export const doSomething = (y) => console.log(y); export default (y) => console.log(y); // myModule.js import * as dependency from './dependency'; export default (x) => { dependency.doSomething(x * 2); dependency.default(x * 2); }; // myModule-test.js import myModule from '../myModule'; import * as dependency from '../dependency'; describe('myModule', () => { it('calls the dependency with double the input', () => { dependency.doSomething = jest.fn(); dependency.default = jest.fn(); myModule(2); expect(dependency.doSomething).toBeCalledWith(4); expect(dependency.default).toBeCalledWith(4); }); });</code>
In this example, we replace import { doSomething } with import * as dependency to import all named exports. We then directly mutate the imported object to mock the exported functions using jest.fn().
The above is the detailed content of How to Effectively Mock ES6 Module Imports in Jest?. For more information, please follow other related articles on the PHP Chinese website!