karma-jasmine

Karma和Jasmine自动化单元测试
前言

在Java领域,Apache, Spring, JBoss 三大社区的开源库,包罗万象,但每个库都在其领域中都鹤立鸡群。而Nodejs中各种各样的开源库,却让人眼花缭乱,不知从何下手。
Nodejs领域: Jasmine做单元测试,Karma自动化完成单元测试,Grunt启动Karma统一项目管理,Yeoman最后封装成一个项目原型模板,npm做nodejs的包依赖管理,bower做javascript的包依赖管理。Java领域:JUnit做单元测试, Maven自动化单元测试,统一项目管理,构建项目原型模板,包依赖管理。

目录
  • Karma的介绍
  • Karma的安装
  • Karma + Jasmine配置
  • 自动化单元测试
  • Karma和istanbul代码覆盖率
  • Karma第一次启动时出现的问题
    1.Karma的介绍
    Karma是Testacular的新名字,在2012年google开源了Testacular,2013年Testacular改名为Karma。Karma是一个让人感到非常神秘的名字,表示佛教中的缘分,因果报应,比Cassandra这种名字更让人猜不透!
    Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其他代码编辑器一起使用。这个测试工具的一个强大特性就是,它可以监控(Watch)文件的变化,然后自行执行,通过console.log显示测试结果。
    Jasmine是单元测试框架,本单将介绍用Karma让Jasmine测试自动化完成。Jasmine的介绍,请参考文章:jasmine行为驱动,测试先行
    istanbul是一个单元测试代码覆盖率检查工具,可以很直观地告诉我们,单元测试对代码的控制程度。
    2.Karma的安装
    系统环境:
    win7 64bit, node v0.10.5, npm 1.2.19
    安装Karma
    ~ D:\workspace\javascript>mkdir karma
    ~ D:\workspace\javascript>cd karma
    ~ D:\workspace\javascript\karma>npm install -g karma
    测试是否安装成功
    ~ D:\workspace\javascript\karma>karma start
    INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/
    INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket nIlM1yUy6ELMp5ZTN9Ek
    3.Karma + Jasmine配置
    初始化karma配置文件karma.conf.js
    ~ D:\workspace\javascript\karma>karma init
    Which testing framework do you want to use ?
    Press tab to list possible options. Enter to move to the next question.

    jasmine

Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.

no

Do you want to capture a browser automatically ?
Press tab to list possible options. Enter empty string to move to the next question.

Chrome

What is the location of your source and test files ?
You can use glob patterns, eg. “js/.js” or “test/**/Spec.js”.
Enter empty string to move to the next question.
>

Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. “*/.swp”.
Enter empty string to move to the next question.
>

Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.

yes

Config file generated at “D:\workspace\javascript\karma\karma.conf.js”.
安装集成包karma-jasmine

~ D:\workspace\javascript\karma>npm install karma-jasmine

4.自动化单元测试
3步准备工作:

  1. 创建源文件:用于实现某种业务逻辑的文件,就是我们平时写的js脚本
  2. 创建测试文件:符合jasmineAPI的测试js脚本
  3. 修改karma.conf.js配置文件
    1). 创建源文件:用于实现某种业务逻辑的文件,就是我们平时写的js脚本
    有一个需求,要实现单词倒写的功能。如:”ABCD” ==> “DCBA”
    ~ vi src.js

function reverse(name){
return name.split(“”).reverse().join(“”);
}
2). 创建测试文件:符合jasmineAPI的测试js脚本

describe(“A suite of basic functions”, function() {
it(“reverse word”,function(){
expect(“DCBA”).toEqual(reverse(“ABCD”));
});
});
3). 修改karma.conf.js配置文件
我们这里需要修改:files和exclude变量

module.exports = function (config) {
config.set({
basePath: ‘’,
frameworks: [‘jasmine’],
files: [‘*.js’],
exclude: [‘karma.conf.js’],
reporters: [‘progress’],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [‘Chrome’],
captureTimeout: 60000,
singleRun: false
});
};
启动karma
单元测试全自动执行

~ D:\workspace\javascript\karma>karma start karma.conf.js
INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
WARN [launcher]: The path should not be quoted.
Normalized the path to C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket bVGffDWpc1c7QNdYye_6
INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket DtTdVbd4ZsgnMQrgye_7
Chrome 28.0.1500 (Windows 7): Executed 1 of 1 SUCCESS (3.473 secs / 0.431 secs)
Chrome 28.0.1500 (Windows 7): Executed 1 of 1 SUCCESS (0.068 secs / 0.021 secs)
TOTAL: 2 SUCCESS
我们修改test.js

~ vi test.js

describe(“A suite of basic functions”, function() {
it(“reverse word”,function(){
expect(“DCBA”).toEqual(reverse(“ABCD”));
expect(“Conan”).toEqual(reverse(“nano”));
});
});
由于karma.conf.js配置文件中autoWatch: true, 所以test.js文件保存后,会自动执行单元测试。
执行日志如下:提示我们单元测试出错了。

INFO [watcher]: Changed file “D:/workspace/javascript/karma/test.js”.
Chrome 28.0.1500 (Windows 7) A suite of basic functions reverse word FAILED
Expected ‘Conan’ to equal ‘onan’.
Error: Expected ‘Conan’ to equal ‘onan’.
at null. (D:/workspace/javascript/karma/test.js:4:25)
Chrome 28.0.1500 (Windows 7): Executed 1 of 1 (1 FAILED) ERROR (0.3 secs / 0.006 secs)
5.Karma和istanbul代码覆盖率
增加代码覆盖率检查和报告,增加istanbul依赖

~ D:\workspace\javascript\karma>npm install karma-coverage
修改karma.conf.js配置文件

~ vi karma.conf.js

reporters: [‘progress’,’coverage’],
preprocessors : {‘src.js’: ‘coverage’},
coverageReporter: {
type : ‘html’,
dir : ‘coverage/‘
}
启动karma start,在工程目录下面找到index.html文件,coverage/chrome/index.html
打开后,我们看到代码测试覆盖绿报告

P.S.

jasmine支持异步测试,这个非常常见!需要好好重视!
在beforeEach、it、和afterEach中,使用done作为函数参数,当异步工作结束以后,这些done函数才会被调用!
例如,在一个describe中,只用当 beforeEach中的done函数被调用了,下面的it中的done才会被调用,直到所有的done函数被调用,整个describe才会结束。
jasmine超时默认等待5秒,可以根据需要设置 jasmine.DEFAULT_TIMEOUT_INTERVAL的值。
对于这个异步测试,还不是很清楚!以后在实践中一定要好好注意!认真总结!
1、spy 可以监听函数是否被调用,以及对应的参数的值!如果被调用 toHaveBeenCalled返回true,如果参数的值是指定的值,则toHaveBeenCalledWith(args)返回true
2、spyOn(….).and.callThrough(),这个函数,比较难懂,附上英文解释:
By chaining the spy with and.callThrough ,the spy will still track all calls to it but in addition it will delegate to the actual implementation.
3、spyOn(…).and.returnValue(val) 这个函数是用val替换监听函数的返回值!
4、spyOn(…).and.callFake(function(){…}) ,这个函数表示结果返回指定的函数。
5、spyOn(…).and.throwError(val),这个函数是用指定的val作为抛出的错误
6、and.stub() 这个方法是配合callThrough使用,相当于取出存根,原来的变量又重获自由!
7、其他跟踪属性:calls,每次调用用spy监听的函数的过程都会被calls跟踪和暴露!
8、xxx.calls.any(),如果监听的函数没有被调用过 返回 false,如果起码调用了一次就返回 true
9、xxx.calls.count(num), 监听函数被调用的次数,num表示几次
10、xxx.calls.argsFor(index), 表示第index次调用监听函数使用的参数
11、xxx.calls.allArgs(),表示所有调用监听函数使用过的参数
12、xxx.calls.all():表示调用监听函数的所有的参数的this上下文内容
13、xxx.calls.mostRecent(),表示返回最近一次调用监听函数的参数的this上下文内容
14、xxx.calls.first(),表示返回第一次调用监听函数的参数的this上下文内容
15、不管all、mostRecent、first都带有object属性,返回的是对象
eg: expect ( xxx.calls.first().object ).toBe( Myobj )
16、xxx.calls.reset(),表示清空监听函数的跟踪信息!

1、Jasmine以 describe开头,里面可以包含多个 it ,而且定义在describe中的变量,任何在describe内声明的 it 都可以调用这个变量,要明确变量的作用域!
2、expect 语法:
expect( exp ).toBe (true / false / undefined)
expect( exp ).not.toBe( true /false / undefined)
3、自定义的匹配测试方法 custom matchers
4、toMatch 专门是为了:正则表达式!
. not . toMatch :(和上面toMatch相反)
5、toBeDefined() 是为了比较是否定义 (‘undefined ’)
. not . toBeDefined() :表示未定义!
6、toBeUndefined() 含义整好和上面的相反, .not.tobeUndefined() 表示已经定义!
7、toBeNull() 匹配变量是否为null,相反加 not 即:.not.toBeNull()
8、toBeTruthy() 表示布尔值的真
toBeFalsy() 表示布尔值的假
9、toContain(‘ele’) 表示数组中是否含 ‘ele’,不包含加 not,即:.not.toContain(‘ele’)
10、toBeLessThan( ‘ele ‘) 小于ele , not.toBeLessThan(‘ ele ‘) 不小于ele
11、 toBeGreaterThan( ‘ele ‘) 大于ele ,不大于 前面加 not
12、toBeCloseTo(ele,num) 比较是否和ele接近,num表示精度
13、toThrow() :表示一个函数抛出异常,不抛出异常,加 not , 即 .not.toThrow()
14、beforeEach(function(){…}) ,全局函数,这个函数在测试之前调用,而且只调用一次!
15、afterEach(function(){…}),全局函数,这个函数在所有测试结束后调用。
16、this关键字,通过this可以在beforeEach、it、afterEach之间共享变量!但是不能在 it….it 之间共享变量!
17、支持嵌套的describe,会依然先访问beforeEach,结束以后再访问afterEach,先由外到里,访问beforeEach,然后再由外向里,访问afterEach。
18、可以设置 xdescribe 和 xit 使对应的代码块不可用!如果设置了,尽管里面的断言代码报错了,也不会被响应
19、pending(),相当于 ”挂起 “ ,如果 it函数声明没有实现function,那么也相当于pending(),测试结果会以黄色的文字显示。

1、jasmine.createSpy(’spyName’):创建监听对象,这个监听对象是JavaScript对象,可以用“笔记二”中的那些属性方法。
2、jasmine.createSpyObj 用于模拟创建多个监听函数,带一个字符串数组 ,它返回一个对象,这个对象的属性就是那些字符串数组的元素。
3、jasmine.any(obj):表示返回obj的构造函数或者类型名称
4、jasmine.objectContaining():表示局部匹配,这个函数不要全看字面意思
5、jasmine.clock().install:当使用setTimeOut和setInterval回调函数时,会模拟一个JavaScript时间回调函数。这个函数使时间回调函数同步,当时间一到就执行注册的函数。
6、相对应的,在结束后使用 jasmine.clock().uninstall,恢复原始的时间调用函数!

问题集锦




解决:如果出现上述问题,则我们就在其所提示的安装路径下全局安装该模块。例如 npm install -g fs-access,如果还缺少其它模块,则处理方式类同。




解决:

P.S. Karma主要设计用来做低层级的测试(单元测试)。如果你想做高层级测试,我们推荐使用protractor

很惭愧<br><br>只做了一点微小的工作<br>谢谢大家