Testing AngularJS applications is easy with Jasmine. If you look at the AngularJS docs, many of the code examples show a corresponding Jasmine spec.
One important part of AngularJS’s testing support is the included angular-mocks.js file. This file contains a module called NgMock that provides a set of fake services for things such as HTTP requests, in order to make them easier to unit test.
As soon as you include this file, the built-in services are overridden with the fake versions. So you should include this file in your Jasmine test environment, but not in your production code.
The Rails asset pipeline makes it easy to version-control and upgrade third party JS libraries such as AngularJS. For instance, there is a popular gem called angularjs-rails that includes all of the AngularJS source files.
Let’s say you have this in your Gemfile:
Whenever you run bundle update angularjs-rails, you will get the latest version of AngularJS in your application without any additional effort. And since angular-mocks.js is included in the gem, its version will also be upgraded in sync.
Unfortunately, up until now, it has been a bit difficult to include asset files from gems into your Jasmine environment using the official Jasmine gem.
- Make a file in your application’s assets, such as app/assets/angular_mocks.js, that requires angular-mocks.js, and include this file in your Jasmine environment, but not in your application. This is strange because you now have test-specific code mixed in with your production code. Also, it becomes easier to accidentally include the NgMock code using something like //= require_tree .
So we decided to improve the situation by changing the Jasmine gem code to add all of the Rails asset pipeline paths into the test environment. We made a pull request, and the code is now available in the latest HEAD version of Jasmine.
Here is a quick example on how you can start testing AngularJS in your application with the new asset pipeline support.
Installing AngularJS and Jasmine
First you need to include angularjs-rails and Jasmine, making sure Jasmine is pointed to HEAD. Then, run Jasmine’s install script.
# ./Gemfile gem "angularjs-rails" gem "jasmine", github: "pivotal/jasmine-gem"
$ bundle install $ rails g jasmine:install
//= require angular-mocks
Running the tests
That’s all the setup you need to know. You can run your specs in the browser using the traditional rake jasmine and start TDDing your new AngularJS app.
For a complete example please refer to this sample app.
About the Author