Karma+Jasmine实现自动化单元测试

 

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显示测试结果。


 

2.Jasmine介绍

Jasmine (茉莉)是一款 JavaScript BDD(行为驱动开发)测试框架,它不依赖于其他任何 JavaScript 组件。它有干净清晰的语法,让您可以很简单的写出测试代码。对基于 JavaScript 的开发来说,它是一款不错的测试框架选择。


3.jasmine基础语法

 
jasmine是一个行为驱动测试JavaScript代码的框架。 它不依赖与任何其他JavaScript框架,也不是必须需要DOM。它有一个干净的,明显的语法,以便你可以轻松的写测试。
 
1)Suites : 套件 (describe Your Tests)

Suite表示一个测试集,以函数describe(string, function)封装,它包含2个参数:
string:测试组名称,
function:测试组函数。

一个Suite(describe)包含多个Specs(it),一个Specs(it)包含多个断言(expect)。

 

2)Specs : 规范

调用全局方法 it 来定义测试规范。它也有两个参数,一个字符串和一个方法。
(1)字符串是这个规范的名称或者标题。
(2)方法就是这个规范或者测试。
一个规范包含一个或者多个测试代码状态的期望值。
一个jasmine的期望值是一个true或者false的断言。所有期望值都是true的规范才是合格的规范,有一个或者多个期望值是false的规范就是失败的规范。
1 describe("A suite",function(){
2     it("contains spec with an expectation",function(){
3         expect(true).toBe(true);
4     });
5 });

3)方法

由于 describe 和 it 块是函数,它们可以包含实现测试所必需的任何可执行代码。JavaScript的作用域规则适用,所以在 describe 的套件里的任何 it 块,变量声明是有效的。
 

4)Expectations :期望值

期望值是用 except 方法来创建的,它需要一个值,称为实际值。这是一个需要期望值的匹配方法链。
 
一个Suite(describe)包含多个Specs(it),一个Specs(it)包含多个断言(expect)。
 

5)Matchers : 匹配器

每一个匹配器实现的是真实值和期望值的比较。它负责报告给jasmine如果期望值是真的或者假的。jasmine将使这个规范通过或者失败。
在调用匹配器之前,通过使用 not 链接调用 except ,任何匹配器可以评估一个反的断言。
1 it("and can have a negative case",function(){
2     expect(false).not.toBe(true);
3 });
 
jasmine包含丰富的匹配器。所有的期望值和规范通过都需要用到。
 
以下测试都是通过的。
 
(1)toBe() : 用来比较数字或者字符串是否相等,不支持对象的比较。
1 describe("Included matchers:",function(){
2     it("The 'toBe' matcher compares with ===",function(){
3         var a =12;
4         var b = a;
5         expect(a).toBe(b);
6         expect(a).not.toBe(null);
7     });
8 }    
 
(2)toEqual() :可以用来比较简单的文本和变量,还有对象是否相等。
 
(3)toMatch():针对正则表达式。
1 it("The 'toMatch' matcher is for regular expressions",function(){
2     var message ='foo bar baz';
3     expect(message).toMatch(/bar/);
4     expect(message).toMatch('bar');
5     expect(message).not.toMatch(/quux/);
6 });
(4)toBeDefined():对未定义进行判断,如果定义了则为true。
 
(5)toBeUndefined():对未定义进行判断,如果没有定义则为true。
 1 it("The 'toBeDefined' matcher compares against `undefined`",function(){
 2     var a ={
 3         foo:'foo'
 4     };
 5     expect(a.foo).toBeDefined();
 6     expect(a.bar).not.toBeDefined();
 7 });
 8 
 9 it("The `toBeUndefined` matcher compares against `undefined`",function(){
10     var a ={
11         foo:'foo'
12     };
13     expect(a.foo).not.toBeUndefined();
14     expect(a.bar).toBeUndefined();
15 });
16     
(6)toBeNull():对空进行比较
1 it("The 'toBeNull' matcher compares against null",function(){
2     var a =null;
3     var foo ='foo';
4     expect(null).toBeNull();
5     expect(a).toBeNull();
6     expect(foo).not.toBeNull();
7 });
 
(7)toBeTruthy():判断布尔值,是布尔值则为true
 
(8)toBeFalsy():判断布尔值,不是布尔值则为true
 
(9)toContain():判断字符串或者数组中是否包含某个值,包含则为true。
 1 describe("The 'toContain' matcher",function(){
 2     it("works for finding an item in an Array",function(){
 3         var a =["foo","bar","baz"];
 4         expect(a).toContain("bar");
 5         expect(a).not.toContain("quux");
 6     });
 7     it("also works for finding a substring",function(){
 8         var a ="foo bar baz";
 9         expect(a).toContain("bar");
10         expect(a).not.toContain("quux");
11     });
12 });
 
(10)toBeLessThan():比较数值大小,若小于则为true。
 
(11)toBeGreaterThan():比较数值大小,若大于则为true。
 1 it("The 'toBeLessThan' matcher is for mathematical         comparisons",function(){
 2     var pi =3.1415926, e =2.78;
 3     expect(e).toBeLessThan(pi);
 4     expect(pi).not.toBeLessThan(e);
 5 });
 6 
 7 it("The 'toBeGreaterThan' is for mathematical comparisons",function(){
 8     var pi =3.1415926, e =2.78, c =3;
 9     expect(c).toBeGreaterThan(e);
10     expect(c).not.toBeGreaterThan(pi);
11 });
 
(12)toBeCloseTo():精密的数学比较
1 it("The 'toBeCloseTo' matcher is for precision math comparison",function(){
2     var pi =3.1415926, e =2.78;
3     expect(pi).not.toBeCloseTo(e,2);
4     expect(pi).toBeCloseTo(e,0);
5 });
 
(13)toThrow():抛出异常时为true
 1 it("The 'toThrow' matcher is for testing if a function throws an         exception",function(){
 2     var foo =function(){
 3         return1+2;
 4     };
 5     var bar =function(){
 6         return a +1;
 7     };
 8     expect(foo).not.toThrow();
 9     expect(bar).toThrow();
10 });
 

4.基本实现

 
1)环境安装
使用npm安装karma:
输入:npm install -g karma  会在全局安装karma, 但是目前还不能使用。
  注:npm install karma --save-dev --save-dev的意思是只有在开发的时候用到这个npm包。但一般是使用上面的方式。
      此时项目没有任何变化。
 
2)配置karma.config.js
输入:karma init
一直回车,直到生成karma.config.js文件。
 1 // Karma configuration
 2 // Generated on Fri Oct 21 2016 12:00:54 GMT+0800 (中国标准时间)
 3 module.exports =function(config){
 4  config.set({
 5  // base path that will be used to resolve all patterns (eg. files, exclude)
 6   basePath:'',
 7 // frameworks to use
 8 // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
 9   frameworks:['jasmine'],
10 // list of files / patterns to load in the browser。!!!这个数组是用来存放被测试代码和测试代码的,默认为空!!!
11   files:[
12   ],
13 // list of files to exclude
14   exclude:[
15   ],
16 // preprocess matching files before serving them to the browser
17 // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
18   preprocessors:{
19   },
20 // test results reporter to use
21 // possible values: 'dots', 'progress'
22 // available reporters: https://npmjs.org/browse/keyword/karma-reporter
23   reporters:['progress'],
24 // web server port
25   port:9876,
26 // enable / disable colors in the output (reporters and logs)
27   colors:true,
28 // level of logging
29 // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
30   logLevel: config.LOG_INFO,
31 // enable / disable watching file and executing tests whenever any file changes
32   autoWatch:true,
33 // start these browsers
34 // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
35   browsers:['Chrome'],
36 // Continuous Integration mode
37 // if true, Karma captures browsers, runs the tests and exits
38   singleRun:false,
39 // Concurrency level
40 // how many browser should be started simultaneous
41   concurrency:Infinity
42   })
43 };
需要注意的是 karma 配置中的 singleRun 这个参数,设置为 false 的话,karma 会自动监控测试环境,默认是 Chrome, 如果你关掉了,karma 会自动重新启动一个。如果配置为 true,执行一次测试之后,karma 会自动停掉。autoWatch:true会自动执行测试用例

这两个参数不需要修改,使用默认值就好。

 

karma 支持三个命令。

  • start [<configFile>] [<options>] 启动 Karma 持续执行,也可以执行单次的测试,然后直接收集测试结果.
  • init [<configFile>] 初始化配置文件.
  • run [<options>] [ -- <clientArgs>] Trigger a test run. 
 
3)安装集成包
输入:npm install karma-jasmine

 

4)新建测试用例

在项目文件夹中,创建一个名为 test 的子文件夹来保存测试用例。然后在 test 文件夹中创建一个 unit 的文件夹来保存单元测试用例。一般来说,我们会为测试用例的文件名称提供一个特定的模式,以便对测试用例进行统一处理,这里我们约定测试用例的文件名以 .spec.js 为结尾。

(1)自定义测试

1 describe('hello',function(){
2     it('test hello',function(){
3        var a ='hello';
4         expect(a).toEqual('hello');
5     });
6 });
(2)测试真实js文件
    add.js
1 function add(a,b){
2     return a + b;
3 }
   add.spec.js
 1 describe('hello',function(){
 2     it('test add',function(){
 3         var a = add(3,6);
 4         expect(a).toEqual(9);
 5     });
 6 
 7     it('test add',function(){
 8         var a = add(3,6);
 9         expect(a).toEqual(10);
10     });
11 });
 

5)修改karma配置文件

确认你的 karma 配置文件中,包含了被测试代码和测试代码。

// list of files / patterns to load in the browser
files: [
    'src/**/*.js',
'test/**/*.spec.js'
],
// list of files to exclude
exclude: [
    'karma.conf.js'
],
 
6)运行测试
输入:karma start karma.conf.js
(直接输入 karma start 也行)
 
报错时:
 
另外,运行之后会生成页面:
 

点击 DEBUG 按钮,可以进入实际的测试页面。

这个页面看起来是空白的,但是执行了实际的测试脚本,右击鼠标点击检查,可以看到实际的内容:

 





原文地址:https://www.cnblogs.com/jasmine-95/p/6054839.html