我有一个 Jest 测试套件无法运行,因为它尝试测试的组件依赖于 RequireJS 模块。这是我看到的错误:
FAIL __tests__/components/MyComponent.test.js
● Test suite failed to run
ReferenceError: define is not defined
at Object.<anonymous> (node_modules/private-npm-module/utils.js:1:90)
该组件具有以下导入:
import utils from 'private-npm-module';
And the private-npm-module
设置如下:
define('utils', [], function() {
return {};
});
When MyComponent
用babel转译并在浏览器中运行,依赖项运行正常。此问题仅影响单元测试。如何让我的测试套件在具有 RequireJS 依赖项的组件上运行?
我在用着babel-jest
as my scriptPreprocessor
在 package.json 的 jest 配置中。我正在使用 jest v0.15.1。
因此,Jest 不支持 RequireJS。在我的具体情况下,最简单、最合适的方法是在顶部嘲笑我的依赖MyComponent.test.js
:
jest.mock('private-npm-module', () => {
// mock implementation
})
import MyComponent from '../../components/MyComponent';
这样,当MyComponent
加载后,它的依赖项已经被模拟,因此它不会尝试加载 RequireJS 模块。
如果您确实需要加载 RequireJS 模块进行测试,则可以使用jest's transform配置 https://jestjs.io/docs/en/configuration#transform-object-string-string将您的实现包装在 RequireJS 到 ES6 转换器中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)