用karma测试angularjs应用

说来惭愧,研究angularjs也有一段时间了,却一直抛弃了angularjs最大的好处之一——测试。这个周末下决心研究下怎么用给angularjs应用做测试。

#安装karma

其实,这么久以来一直没用到angularjs的测试就是因为不会配置karma。因为项目一开始的时候看着文档跑了一遍,没跑成功就放下了。这两天有细读了文档,发现当初也不能全怪我笨,angularjs的文档写的确实操蛋。karma都更新好多了,它还是旧的文档、代码,难怪我跑不通。

好了,开始安装karma。

第一: 打开cmd,输入> npm install -g karma 就行了

第二:配置文件,这个版本(0.10)配置挺简单的,有提示,一步步确认就行了。

第三:(文档里没写,从错误信息里看出来的)设置环境变量  CHROME_BIN  "你的chrome安装路径"。这一步至关重要,因为自己安装chrome时的一些设置,karma在系统默认的一些变量里找不到chrome浏览器,就会导致测试失败。当初大概也是被绊倒在这里的。

剩下的就简单了,自己在命令行里生成一个karma配置文件替换掉angualr-phonecat里的karma配置文件就OK了。下面是我生成的配置文件demo,亲测在windows 7下OK

// Karma configuration
// Generated on Sun Aug 18 2013 16:26:13 GMT+0800 (中国标准时间)

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '../',


    // frameworks to use
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
        'app/lib/angular/angular.js',
        'app/lib/angular/angular-*.js',
        'test/lib/angular/angular-mocks.js',
        'app/js/**/*.js',
        'test/unit/**/*.js'
    ],


    // list of files to exclude
    exclude: [
      
    ],


    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    reporters: ['progress'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],


    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};

原文地址:https://www.cnblogs.com/chaos-forfun/p/3266166.html