2015-07-21 67 views
6

我遇到了一個問題,我需要在由Webpack構建的React應用程序上運行Jest測試。問題在於處理Webpack通常使用加載程序處理的CSS文件和圖像的require。我需要知道什麼是正確測試我的組件的最佳方法。測試Webpack構建的React組件與Jest

的陣營組成:

import React from 'react'; 
// The CSS file is the problem as I want to actually test what it 
// returns after webpack has built it. 
import style from './boilerplate.css'; 

var Boilerplate = React.createClass({ 
    render: function() { 
     return (
      <div> 
       <h1 className={style.title}>react-boilerplate</h1> 
       <p className={style.description}> 
        A React and Webpack boilerplate. 
       </p> 
      </div> 
     ); 
    } 
}); 

export default Boilerplate; 

的玩笑測試:

jest.dontMock('./boilerplate.js'); 

var Boilerplate = require('./boilerplate.js'); 
var React = require('react/addons'); 
var TestUtils = React.addons.TestUtils; 

describe('boilerplate', function() { 

    var component; 

    beforeEach(function() { 
     component = TestUtils.renderIntoDocument(
      <Boilerplate /> 
     ); 
    }); 

    it('has a h1 title', function() { 
     // I want to actually use 'findRenderedDOMComponentWithClass' 
     // but cannot because I need to run the Webpack build to add a 
     // CSS class to this element. 
     var title = TestUtils.findRenderedDOMComponentWithTag(component, 'h1'); 
     expect(title.getDOMNode().textContent).toEqual('react-boilerplate'); 
    }); 

    it('has a paragraph with descriptive text', function() { 
     var paragraph = TestUtils.findRenderedDOMComponentWithTag(component, 'p'); 
     expect(paragraph.getDOMNode().textContent).toEqual('A React and Webpack boilerplate.'); 
    }); 

}); 

我所遇到this question這安慰我,我是在嘗試過右線所有這些方法自己但我遇到了所有我遇到的解決方案問題:

解決方案1: 使用scriptPreprocessor文件剝離了的那些需要的WebPack建立e.g需要.css.less.jpegs等。這樣我們就可以測試做出反應成分,但沒有其他非Javascript文件requires

問題:我想測試一下Webpack構建的一些功能。例如,我使用本地可互操作的CSS,並且我想測試從Webpack創建的require('whaterver.css')返回的CSS類對象。我也想使用React/TestUtils中的findRenderedDOMComponentWithClass,這意味着我需要通過Webpack構建CSS。

解決方案2: 使用scriptPreprocessor腳本穿過的WebPack運行成分和構建的測試文件(如jest-webpack那樣),在此輸出運行測試。

問題:我們不能再使用Jest的自動模擬,因爲我們現在使用Webpacks __webpack_require__(1)。每次運行測試文件時,這樣做的速度也很慢。

解決方案3: 就像解決方案2,但運行npm test解決緩慢的構建時間之前只能運行一個針對所有測試文件版本。

問題:與解決方案2相同。沒有自動模擬。

我在這裏錯誤的路徑或沒有人有任何答案嗎?我錯過了明顯嗎?

回答

3

我最近創建了Jestpack,它集成了Jest和Webpack,這意味着您可以使用Webpack的所有功能,包括CSS模塊,文件加載,代碼分割,CommonJS/AMD/ES2015導入等等以及Jest的自動模擬。