首页 文章

在测试具有RequireJS依赖性的es6模块时,在Jest中“定义未定义”

提问于
浏览
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 {};
});

使用babel转换 MyComponent 并在浏览器中运行时,依赖项可以正常运行 . 此问题仅影响单元测试 . 如何让我的测试套件在具有RequireJS依赖关系的组件上运行?

我在package.json 's jest config. I' m中使用 babel-jest 作为我的 scriptPreprocessor 使用jest v0.15.1 .

1 回答

  • 9

    因此,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转换器中 .

相关问题