2016-12-01 61 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轉換器中。