AngularJS单元测试——karma+mocha配置及实例

来源:互联网 发布:c语言写gui 编辑:程序博客网 时间:2024/05/20 20:18

参考链接:http://www.tuicool.com/articles/yuMvQz
(注:有所修改)

什么是Karma?

mocha是一个js的测试框架,之前写过的一篇博客介绍了如何用node.js的环境来运行测试。Karma是一个驱动测试的Runner。也就是说,karma为测试框架准备运行环境,可以让这些测试在真正的浏览器里运行。

而且,karma运行测试的过程是自动化的。自动化并非理所当然的事。想起之前用Jasmine的时候,需要在一个html文件里引入各种js文件,然后用某个浏览器来打开这个html文件,使js在浏览器中运行起来。当测试内容发生变化时,需要刷新页面,并时不时地清空缓存。。。有了karma,就省事多啦~而且不需要额外的配置,karma就会自己找到系统已经装好的浏览器并启动。

karma支持的测试框架还有Jasmine和Qunit。

环境搭建

假设已经搭建好了node.js平台
先全局安装mocha和karma的命令行接口karma-cli(Linux下有可能需要sudo权限):
(-g 表示全局范围)

npm install -g mochanpm install -g karma-cli

可能遇到的问题

1.需要安装Python 且版本要介于2.5.0到3.0.0,建议安装2.7。
2.需要安装VS(建议VS2013)。

要测试的文件目录结构如图:
这里写图片描述

先在demo-karma-mocha目录下运行 npm install 安装package.json里的依赖,package.json内容如下:

  //package.json  {    "name": "karma-mocha-example",    "version": "0.0.0",    "description": "This is an example to show how to use karma with mocha",    "main": "index.js",    "dependencies": {      "karma": "~0.10.8"    },   "devDependencies": {     "mocha": "~1.18.0",     "karma-mocha": "~0.1.3",     "should": "~2.1.1",     "karma-chrome-launcher": "~0.1.2",     "karma-firefox-launcher": "~0.1.3"   } }

现在解析一下demo-karma-mocha这个目录的结构。

node_modules是npm依据package.json下载的包,src是源文件目录,test是测试文件目录。

test-lib目录下的should.js是mocha测试要用到的断言库。找到node_modules/should/should.js,将其复制到test-lib目录下。

karma.conf.js描述了karma测试的配置信息,在该目录下运行karma start时,会默认从该文件中读取信息。可以通过在该目录下运行karma init的方式来帮助生成karma.conf.js文件。

配置karma.conf.js

运行karma init后,karma会提一些问题,可以通过按tab键来切换选项(第一个是选择框架,默认是jasmine,所以要按Tab来切换)。如果一些选项需要依赖某些未安装的npm包,karma也会提醒你之后用什么命令来安装这些依赖。

当karma问道:”what is the location of your source and test file”时,依次输入 src /**/ *.js , test-lib /**/ *.js , test /**/ *.js ,表示要运行src、test-lib、test中的所有js文件。

(注:由于是AngularJS应用,免不了要引入angular的js文件,所以建议在前面加上需要的js文件:例如:angular.js angular-mocks.js。 在html中引入是要使用相对路径,避免重复加载js文件)

值得注意的是,autoWatch这一属性最好选择true,这样,karma会在指定目录有更新时自动跑测试。

本例中karma.conf.js文件的内容如下,设置了同时在Chrome和Firefox这两个浏览器里里运行测试:

 module.exports = function (config) {    config.set({        // base path that will be used to resolve all patterns (eg. files, exclude)        basePath: '',        // frameworks to use        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter        frameworks: ['mocha'],        // list of files / patterns to load in the browser        files: [            //引入外部js            'angular.js',            'angular-mocks.js',            'src/**/*.js',            'test/*.js',            'test-lib/**/*.js'        ],        // list of files to exclude        exclude: [],        // preprocess matching files before serving them to the browser        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor        preprocessors: {},        // test results reporter to use        // possible values: 'dots', 'progress'        // available reporters: https://npmjs.org/browse/keyword/karma-reporter        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        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher        browsers: ['Chrome'],        // Continuous Integration mode        // if true, Karma captures browsers, runs the tests and exits        singleRun: false,        // Concurrency level        // how many browser should be started simultanous        concurrency: Infinity    })}

View Code - karma.conf.js

运行测试

要测试的内容很简单,就是看sayHi这个函数能不能在有输入时跟人打个招呼:

 //greetings.js function sayHi(name){     return name ? "Hi " + name : "Nobody comes"; }

相应的测试代码写在greeting-spec.js中:
(注:大部分书籍都是以jasmine作为测试框架,所以语法与mocha不尽相同,如:toEqual( )→should.equal( ), 而且没有expect这个函数。注意函数的正确性)

  //greetings-spec.js  describe("Counter", function() {      it("should say Hi given a name", function() {          sayHi("Tom").should.equal("Hi Tom");      });      it("should not say Hi if no input", function() {          sayHi().should.equal("Nobody comes");     }); });

直接在demo-karma-mocha下运行 karma start 就可以启动两个浏览器并运行测试了,测试的结果会在命令行中显示。

由于设置了 autoWatch: true ,当改变src、test-lib、test文件夹中的任意一个文件时,karma都会重新运行所有测试。

如果autoWatch的值为false,则在 karma start 后,还需要 karma run 来手动运行每一次测试。

问题

这样还仍然不够方便。

比如,虽然用npm引入了should.js,却还要在node之外手动地将should.js放在test-lib中。而且,为了让其在浏览器里运行,这个程序没有用到node.js模块化的功能。这一点可以用 browserify来解决,把运行在后端的js代码转换为浏览器能运行的代码。

另外,grunt也可以集成karma,用它来运行karma测试就更方便了。


附上一些参考链接:
http://mochajs.org/
https://www.npmjs.com/
https://github.com/shouldjs/should.js(should断言的语法)

0 0