Setting up React tests with Mocha and Webpack

Writing unit for React classes written with ES6 is a bit less simple than for plain old ES5 JavaScript. The extra compilation steps mean that the production source files and the test code both need to be compiled before running.

To perform this role I'm using Webpack.  Webpack provides bundling and compilation bringing my source code (test or production) down into one big ES5 file.

To get Mocha tests running with Webpack.

Getting a basic test running

To get a basic test running, nothing  more than vanilla ES5 Java Script.
  • Include the Mocha loader (npm install mocha-loader)
  • Navigate to your test directory. 
  • Run "webpack mocha!./testroot.js testBundle.js"
  • Create an empty html file that includes testBundle.js after the body. 
  • Open the html file.

Using a config file

Obviously we want to use more than just Vanilla.js we want to include React and ES6 components. 

To do this I'm using a second config file, in addition to the one used to compile the client in to bundle.js,  This is in the root directory of the project next to the webpack.config.js file.



You can run webpack using this config file by specifying the config file explicitly.  "webpack --progress --colors --config ./test.webpack.config.js"

Open the html file from before, make sure it points to the same testBundle.js that you're config is spitting out.

Now you can start including and testing your React components.

Comments

Popular posts from this blog

Solving `Empty reply from server` in DotNet Core

Testing functions that use local storage with Jest

Can't resolve DNS Aws