【问题标题】:"Define is not defined" in Jest when testing es6 module with RequireJS dependency测试具有 RequireJS 依赖项的 es6 模块时,Jest 中的“未定义定义”
【发布时间】:2017-04-16 14:04:11
【问题描述】:

我有一个无法运行的 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 的 jest 配置中使用 babel-jest 作为我的 scriptPreprocessor。我正在使用 jest v0.15.1。

【问题讨论】:

标签: reactjs webpack babeljs jestjs babel-jest


【解决方案1】:

所以,Jest 不支持 RequireJS。在我的特殊情况下,在MyComponent.test.js 顶部模拟我的依赖项是最简单和最合适的:

jest.mock('private-npm-module', () => {
  // mock implementation
})

import MyComponent from '../../components/MyComponent';

这样,当MyComponent被加载时,它的依赖已经被mock了,所以它不会尝试加载RequireJS模块。

如果您确实需要为测试加载 RequireJS 模块,可以使用 jest's transform configuration 将您的实现包装在 RequireJS 到 ES6 转换器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-19
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 2015-08-25
    • 2016-07-12
    相关资源
    最近更新 更多