AngularJS Web Application Development Blueprints
上QQ阅读APP看书,第一时间看更新

Unit testing with Karma

Writing automated unit tests for your AngularJS app is one of the best practices, the AngularJS team has been strongly advocating this right from the start. Every sample code on the has automated test cases along with it.

Keeping in line with the same philosophy, Yeoman too bakes in some sample unit tests using Karma. While Yeoman would automatically install Karma and its dependencies, let us, nevertheless, make sure the following modules are present in the node_modules folder:

  • karma
  • karma-chrome-launcher
  • karma-jasmine

In case you don't find them in your node_modules folder, install them using the npm install command. Next, make sure your karma.conf.js file looks like the following:

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
  'bower_components/angular/angular.js',
  'bower_components/angular-mocks/angular-mocks.js',
  'bower_components/angular-animate/angular-animate.js',
  'bower_components/angular-resource/angular-resource.js',
  'bower_components/angular-cookies/angular-cookies.js',
  'bower_components/angular-route/angular-route.js',
  'bower_components/angular-sanitize/angular-sanitize.js',
  'bower_components/angular-touch/angular-touch.js',
  'app/app.js',
  'app/scripts/*.js',
  'app/scripts/**/*.js',
  'test/spec/**/*.js'
    ],
    exclude: [
      
    ],
    preprocessors: {
    
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

To run your unit tests, simply run the following command in the terminal:

grunt test

This will fire up a new Chrome browser window and in the terminal start running through your tests. Refer to the following screenshot:

Oh! We got an error in MainCtrl. It would say something like Expected 5 to be 3 and point you to an error in the file located at test/spec/controllers/main.js.

Let's open up this file and see what's going on in there. The test case that's failing is as follows:

it('should attach a list of awesomeThings to the scope', function() {
    expect(scope.awesomeThings.length).toBe(3);
});

If you recollect, earlier we had modified our awesomeThings controller and added some additional elements to the array, the preceding test case is expecting the length of that array to be 3. Let's now modify that statement to the following code:

expect(scope.awesomeThings.length).toBeGreaterThan(3);

Let's save this file and rerun the following command:

grunt test

The test cases should run fine with a message saying Executed 2 of 2 SUCCESS……. Done, without errors. We will be writing more unit tests with Karma in the forthcoming chapters.