reactjs - Testing Webpack built React components with Jest -
i have come across problem need run jest tests on react application being built webpack. problem handling require
of css files , images etc webpack process loader. need know best approach test components correctly.
the react component:
import react 'react'; // css file problem want test // returns after webpack has built it. import style './boilerplate.css'; var boilerplate = react.createclass({ render: function() { return ( <div> <h1 classname={style.title}>react-boilerplate</h1> <p classname={style.description}> react , webpack boilerplate. </p> </div> ); } }); export default boilerplate;
the jest test:
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 h1 title', function() { // want use 'findrendereddomcomponentwithclass' // cannot because need run webpack build add // css class element. var title = testutils.findrendereddomcomponentwithtag(component, 'h1'); expect(title.getdomnode().textcontent).toequal('react-boilerplate'); }); it('has paragraph descriptive text', function() { var paragraph = testutils.findrendereddomcomponentwithtag(component, 'p'); expect(paragraph.getdomnode().textcontent).toequal('a react , webpack boilerplate.'); }); });
i have come across this question reassured me on right lines having tried these approaches myself have issues of solutions have come across:
solution 1: use scriptpreprocessor
file strips out requires
of non javascript files require webpack build e.g requiring .css
, .less
, .jpegs
etc. way can tests react component nothing else.
problem: want test of functionality webpack build creates. e.g use local, interoperable css , want test object of css classes returned require('whaterver.css')
webpack creates. want use findrendereddomcomponentwithclass
react/testutils
means need build css through webpack.
solution 2: use scriptpreprocessor
script runs component through webpack , builds test file (like jest-webpack does) , run tests on output.
problem: can no longer use jest's auto mocking using webpacks __webpack_require__(1)
. slow build every time run test file.
solution 3: solution 2 run 1 build test files before running npm test
solve slow build time.
problem: same solution 2. no auto mocking.
am on wrong path here or have answers this? missing obvious?
i built jestpack integrates jest webpack meaning can use of webpack's features including css modules, file loading, code splitting, commonjs / amd / es2015 imports etc. along jest's auto mocking.
Comments
Post a Comment