I ran into a problem when I need to run Jest tests in a React application that Webpack creates. The problem is the processing of require files and CSS images, etc., which Webpack normally handled using a loader. I need to know what works best for testing my components.
React Component:
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 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 a h1 title', function() {
I came across this question , which assured me that I was on the right track, having tried all these approaches myself, but I have problems with all the solutions that I came through:
Solution 1: Use a scriptPreprocessor file that cuts out requires non-Javascript files that require a Webpack assembly, such as those requiring .css , .less , .jpegs , etc. Thus, we can test the React component, but nothing more.
Problem. I want to check out some of the features that the Webpack assembly creates. For example, I use local, compatible CSS, and I want to test the CSS class classes returned with require('whaterver.css') , which Webpack creates. I also want to use findRenderedDOMComponentWithClass from React/TestUtils , which means I need to create CSS via Webpack.
Solution 2: Use a scriptPreprocessor script that runs the component through Webpack and creates a test file (for example, jest-webpack ) and runs the tests on this output.
Problem: we can no longer use Jest auto mocking, because now we will use Webpacks __webpack_require__(1) . It is also slow to create every time you run a test file.
Solution 3: Like solution 2, but run only one build for all test files before running npm test to solve the slow build time.
Problem: same as in solution 2. No automatic bullying.
Am I on the wrong track here, or does anyone have answers to this? Am I missing the obvious?