官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 顺昌县| 元朗区| 纳雍县| 岳阳县| 紫云| 怀远县| 布拖县| 淮北市| 尉氏县| 醴陵市| 大足县| 马龙县| 宁夏| 虞城县| 扎兰屯市| 长海县| 安阳市| 怀远县| 葵青区| 定边县| 江门市| 安溪县| 巨鹿县| 温宿县| 苍梧县| 广东省| 通化市| 广平县| 成安县| 长寿区| 德兴市| 鹤山市| 家居| 仪陇县| 桐乡市| 泽库县| 武夷山市| 神池县| 大冶市| 永靖县| 龙泉市|