Previously I showed how to write application code using ES6, but wouldn't it be nice to use ES6 when writing unit tests as well? In the following post I will demonstrate how to write Jasmine tests using ES6 syntax.
Setting up the test environment is fairly easy, but to move things along I've included my sample package.json configuration
I will be using Karma to run the tests, so the next step is to add a karma.config.js file to your project.
I have chosen to run my tests using PhantomJS – a headless browser ideal for these types of tasks.
Babel is used for transpiling ES6 to ES5.The last bit of plumbing is to add test-context.js to your project:
This is where you tell the test runner where your files are located. Based on the configuration above my test files are located in ./source and they all end in -spec.js. The extra boolean flag indicates if you want it to go looking for files in subdirectories under ./source.
context.keys contains an array of test files.
Now that the environment is bootstrapped it's time to write some tests!
To keep it simple we will be writing tests for a simple calculator implementation.
The calculator supports adding and subtracting so we will write a test for both operations.
As you can tell the Jasmine tests are all defined using ES6.
Earlier we defined a task for running the tests, so to kick off the tests, simply execute the following command:
I found the following article to be very helpful when playing around with this:http://kentor.me/posts/testing-react-and-flux-applications-with-karma-and-webpack/
I have put the code up on Github