Unit testing in JavaScript – Jasmine 2.0 + RequireJS + JSCover + PhantomJS

It took me a while to setup unit testing in JavaScript project I’m involved in. I must say the task was so difficult to me that I’ve decided to share my experience and final setup. Not that unit testing itself is hard. PHP, Ruby, Java… never had any problems. JavaScript was a long ride.

My setup consist of the following tools:

  • Jasmine 2.0 (previously 1.3) – unit testing library
  • RequireJS – AMD library
  • JSCover – test coverage tool, supporting lines of code, branches and functions coverage metrices
  • PhantomJS – headless browser

Folders structure separates the tools used, unit tests, project source code and libraries project depends on from each other, so that adapting it to any project should be straight forward:

The actual setup can be cloned from github:

https://github.com/wojciechszela/jasmine-requirejs-jscover

and it comes with few JavaScript classes under test and their corresponding unit tests. Please excuse the quality of tests and classes. They serve just as proof of setup.

To use it as is Ant is needed. Just run

 

without any other parameters and it will print you short help. To run unit tests run “unittest” target:

Generating coverage report requires having JSCover running:

The report will be stored in “build/coverage” folder.

Ant build script is mostly about starting/stopping JSCover and running PhantomJS (unit tests via PhantomJS) – it should be fairly simple to port it to Maven, Grunt or any other build tool. There is only one thing that needs to be taken care when porting, that is, generating application.js file. This file loads all application code using require method of RequireJS. Again, generating this file using any other build tool should be easy.

I hope that you will find this setup useful and it will save you time trying to get Jasmine, RequireJS, PhantomJS and JSCover to work together.