How to configure Jasmine test with React, ES6 and Webpack
If you created your app using
react_create_app, congrats! You saved you saved yourself some time. You now have
jest up and running correctly. But chances are you configured your
Webpack and now you want to configure
Jasmine to test your components and do unit testing. Let’s see how can we do that:
To run your test cases and access jasmine from the command line you will want to install jasmine globally.
npm install -g jasmine
Jasmine needs some configuration to know where your tests are and what needs to be done with them. Run the below command to initialize the repository.
This command will create a
jasmine.json file, which will look like this:
P.S. Please remove all comments if you copy the above json
Make jasmine understand ES6
Jasmine cannot understand ES6 syntax by default. So we will have to use
babel. Install babel like so:
npm install babel-cli
Now create a file called as
run.js you can place it anywhere, I like to keep it in
spec/, which should look like this:
Run the test
Finally to run the test, add the following line inside
scripts section of your
Ensure you point to your
npm test will run all your test cases in the spec path specified in jasmine.json file.
Bonus: handling webpack alias
You should be all good to go, but in case you had some
aliases in your webpack config then you will need to follow this step. Install
module-alias like so:
npm install --save module-alias
Then add following line of code in your
package.json at the end:
feel free to change the aliases above, in my case, I had two aliases called as vendor and js. Now in order to get this aliases load before your test start, you will have to create a file in
helper/, I will called it
In that file all you have to do is paste these lines of code:
Now run your tests as usual and everything should work.
I hope this was helpful. If you find something which can be improved please let me know in the comments below. Thanks for reading.
Ankit Singhaniya is a Full Stack Developer. He loves to explore new technology and make things easy for everyone. He loves Rails, React, Python, Java and more open source technologies..