2016-12-01 59 views
4

我有一个Jest测试套件无法运行,因为它试图测试的组件取决于RequireJS模块。下面是我看到的错误:在Jest测试依赖于RequireJS的es6模块的“定义未定义”

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被transpiled与babel并在浏览器中运行,依赖关系正常运行。此问题仅影响单元测试。如何让我的测试套件在具有RequireJS依赖项的组件上运行?

我在package.json的jest config中使用babel-jest作为我的scriptPreprocessor。我正在使用jest v0.15.1。

回答

3

所以,RequireJS不被Jest支持。在我的具体情况,这是最简单,最合适的嘲笑在MyComponent.test.js上面有我的依赖性:

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

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

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

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