相关疑难解决方法(0)

Jest模拟默认导出 - 需要vs导入

我在这里看到有关嘲笑默认出口的问题,但我不认为这已经被问到:

在模拟正在测试的模块的依赖项的默认导出TypeError: (0 , _dependency.default) is not a function时,如果模块使用ES6 import语句导入依赖项,则测试套件无法运行,但是,如果模块使用require().default调用,则说明它成功.

根据我的理解,import module from location直接转换为const module = require(location).default,所以我很困惑为什么会发生这种情况.我宁愿保持我的代码风格一致,也不要require在原始模块中使用调用.

有办法吗?

使用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();
});
Run Code Online (Sandbox Code Playgroud)

Dependency.js

export default () => console.log('do something');
Run Code Online (Sandbox Code Playgroud)

module.js(不工作)

import dependency from './dependency.js';
dependency();
Run Code Online (Sandbox Code Playgroud)

module.js(工作)

const dependency …
Run Code Online (Sandbox Code Playgroud)

javascript jestjs es6-modules

7
推荐指数
4
解决办法
5210
查看次数

标签 统计

es6-modules ×1

javascript ×1

jestjs ×1