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的规范就是失败的规范。
 describe("A suite",function(){
it("contains spec with an expectation",function(){
expect(true).toBe(true);
});
});

3)方法

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

4)Expectations :期望值

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

5)Matchers : 匹配器

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

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文件。
 // Karma configuration
// Generated on Fri Oct 21 2016 12:00:54 GMT+0800 (中国标准时间)
module.exports =function(config){
config.set({
 // base path that will be used to resolve all patterns (eg. files, exclude)
6   basePath:'',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
  frameworks:['jasmine'],
// list of files / patterns to load in the browser。!!!这个数组是用来存放被测试代码和测试代码的,默认为空!!!
  files:[
  ],
// 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
25   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
38   singleRun:false,
// Concurrency level
// how many browser should be started simultaneous
  concurrency:Infinity
})
};
需要注意的是 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)自定义测试

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

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 按钮,可以进入实际的测试页面。

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

Karma+Jasmine实现自动化单元测试的更多相关文章

  1. 搭建Karma+Jasmine的自动化单元测试

    最近在打算将以前的代码进行重构,过程中发现自己不写自动化测试代码,而是手动的写,这样并不好,所以就学了Karma+Jasmine的自动化单元测试,以后写代码尽量要写自动化单元测试,也要测一下istan ...

  2. 在WebStorm中集成Karma+jasmine进行前端单元测试

    在WebStorm中集成Karma+jasmine进行前端单元测试 前言 好久没有写博了,主要还是太懒=.=,有点时间都去带娃.看书了,今天给大家分享一个原创的小东西,如果大家对TDD或者BDD有兴趣 ...

  3. Karma和Jasmine自动化单元测试

    从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的Javascript引擎.chrome浏 ...

  4. Karma和Jasmine 自动化单元测试环境搭建

    最近初学AngularJS ,看到的一些教程中经常有人推荐使用Karma+Jasmine来进行单元测试.自己之前也对Jasmine有些了解,jasmine也是一个不错的测试框架. 1. karma介绍 ...

  5. 学习Karma+Jasmine+istanbul+webpack自动化单元测试

    学习Karma+Jasmine+istanbul+webpack自动化单元测试 1-1. 什么是karma?  Karma 是一个基于Node.js的Javascript测试执行过程管理工具.该工具可 ...

  6. Karma和Jasmine自动化单元测试——本质上还是在要开一个浏览器来做测试

    1. Karma的介绍 Karma是Testacular的新名字,在2012年google开源了Testacular,2013年Testacular改名为Karma.Karma是一个让人感到非常神秘的 ...

  7. karma、jasmine做angularjs单元测试

    引用文:karma.jasmine做angularjs单元测试 karma和jasmine介绍 <1>技术介绍 karma karma是Testacular的新名字 karma是用来自动化 ...

  8. 使用karma+jasmine做单元测试

    目的 使用karma和jasmine来配置自动化的js单元测试. Karma和Jasmine Karma是由Angular团队所开发的一种自动化测试工具.链接:http://karma-runner. ...

  9. 利用Angularjs测试引擎Karma进行自动化单元测试

    Karma是Google用于angularjs框架单元测试的js引擎(javascript test runner ), angular1 和angular2项目源码的单元测试都是基于karma和ja ...

随机推荐

  1. Emmet,让你爱上敲代码

    原文链接:http://m.blog.csdn.net/article/details?id=53484535 不错 —— 由 都不要欺负我 分享 Emmet 是一个可用在许多流行文本编辑器上的极大简 ...

  2. 学习android推荐网站

    1. Android Developers 作为一个Android开发者,官网的资料当然不可错过,从设计,培训,指南,文档,都不应该错过,在以后的学习过程中慢慢理解体会. 2. Android Gui ...

  3. tp框架之空方法与空控制器

    对于空方法的两种方法: 1.建立一个empty模板(不建议,除非打算指定静态页面) 2.在控制器里面加一个empty方法 public function _empty() { echo "控 ...

  4. OpenStack 云计算基础知识

    OpenStack Docs: Currenthttp://docs.openstack.org/ OpenStack云计算快速入门教程 - OpenStack及其构成简介_服务器应用_Linux公社 ...

  5. 【leetcode】Unique Binary Search Trees (#96)

    Given n, how many structurally unique BST's (binary search trees) that store values 1...n? For examp ...

  6. Channel

    提起Channel,JDK的NIO类库的重要组成部分,就是提供了java.nio.SocketChannel和java.nio.ServerSocketChannel,用于非阻塞的I/O操作. 类似于 ...

  7. PHPExcel——读取excel

    在网上找了excel读取的一些资料,个人觉得PHPExcel这还是挺好用的,相对比较全的工具. 主要功能是读取上传的excel文件,插入或更新到数据库. iconv("gbk",& ...

  8. 【转】前端工程筹建NodeJs+gulp+bower

    转自:http://www.myexception.cn/javascript/1781968.html npm nodejs 安装过程中会自动安装npm,nodejs安装程序会在环境变量中添加两个变 ...

  9. Python for Infomatics 第13章 网页服务一(译)

    注:文章原文为Dr. Charles Severance 的 <Python for Informatics>.文中代码用3.4版改写,并在本机测试通过. 一旦利用程序通过HTTP协议获得 ...

  10. Web前端学习过程

    推荐学习网站www.freecodecamp.cn http://www.w3school.com.cn/ 步骤: 作者:张帅 知乎链接:https://www.zhihu.com/question/ ...