"Define is not defined" 在测试带有 RequireJS 依赖的 es6 模块时在 Jest 中
"Define is not defined" in Jest when testing es6 module with RequireJS dependency
我有一个 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';
private-npm-module
设置如下:
define('utils', [], function() {
return {};
});
当 MyComponent
在浏览器中用 babel 和 运行 转译时,依赖项运行正常。此问题仅影响单元测试。如何让我的测试套件在具有 RequireJS 依赖项的组件上 运行?
我在 package.json 的玩笑配置中使用 babel-jest
作为我的 scriptPreprocessor
。我正在使用 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
configuration 将您的实现包装在 RequireJS 到 ES6 转换器中。
我有一个 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';
private-npm-module
设置如下:
define('utils', [], function() {
return {};
});
当 MyComponent
在浏览器中用 babel 和 运行 转译时,依赖项运行正常。此问题仅影响单元测试。如何让我的测试套件在具有 RequireJS 依赖项的组件上 运行?
我在 package.json 的玩笑配置中使用 babel-jest
作为我的 scriptPreprocessor
。我正在使用 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
configuration 将您的实现包装在 RequireJS 到 ES6 转换器中。