jasmine+karma 自动化单元测试

测试的必须性

相信你们都知道测试的必要性,测试先行的概念。不过,写了这么多年的代码,除了以前用java的时候写过一些测试用例,还真的不多写过前端的测试用例,或者作一些自动化测试。感受作单元测试仍是颇有必须的,它能帮助你整理思路,换个角度思考问题,发现bug。最近正好研究一下,以前了解到jasmine是作js单元测试的利器,karma是用来自动化运行分析统计单元测试的,结合karma-coverage还能统计代码覆盖率,这么牛的神器,必定要试一试。另外最后会介绍另一个端到端的测试神器protractor,不过目前只能测试angular的应用。javascript

 

 

转载请注明出处:http://www.haomou.net/2015/03/10/2015_karma_jasmine/css

karma安装及使用

Karma是Testacular的新名字,在2012年google开源了Testacular,2013年Testacular更名为Karma。Karma是一个让人感到很是神秘的名字,表示佛教中的缘分,因果报应,比Cassandra这种名字更让人猜不透!html

Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试全部主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其余代码编辑器一块儿使用。这个测试工具的一个强大特性就是,它能够监控(Watch)文件的变化,而后自行执行,经过console.log显示测试结果。前端

官网:https://karma-runner.github.iojava

安装karma

  1. 安装nodejs,注意相关版本要求node

  2. 安装karma和相关插件,推荐的方法是在项目目录安装karma和相关插件git

1
2
3
4
5
# Install Karma:
$ npm install karma --save-dev
# Install plugins that your project needs:
$ npm install karma-jasmine karma-chrome-launcher --save-dev

上面的命令会安装karma, karma-jasmine 和 karma-chrome-launcher 到node_modules目录,同时将配置保存到package.json中。接着能够运行karmaangularjs

1
2
# Run Karma:
$ ./node_modules/karma/bin/karma start

注意,直接运行karma是不行的,确定会报错,须要用上面的方法运行。若是想直接用karma命令,须要安装karma-cli,以下所示:github

1
$ npm install -g karma-cli

而后你就能够直接运行karma命令了。web

咱们执行

1
2
3
./node_modules/karma/bin/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

能够看到karma会自动打开浏览器,界面以下:

 

初始化karma配置

执行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
./node_modules/karma/bin/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介绍

jasmine是为javascript提供的行为驱动的测试开发框架,它不依赖于浏览器,DOM,或者其余javascript框架,能够为web项目,node项目或者其余运行js的项目写单元测试。

官网:http://jasmine.github.io

使用文档api介绍:http://jasmine.github.io/2.0/introduction.html

运行示例

咱们假设在当前目录,按照上面的方法安装了karma,(须要注意的是上面安装karma的时候已经安装了jasmine),而后咱们作个测试。

  1. 编写源文件src.js
1
2
3
function reverse(name){
return name.split("").reverse().join("");
}
  1. 编写测试代码test.js
1
2
3
4
5
describe("A suite of basic functions", function() {
it("reverse word",function(){
expect("DCBA").toEqual(reverse("ABCD"));
});
});
  1. 修改karma.conf.js配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
});
};

刚才经过命令行的方式生成的配置文件和上面的可能有所不一样,做参考。

  1. 启动karma测试
1
2
3
4
5
6
7
8
9
10
11
./node_modules/karma/bin/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

会自动打开浏览器

 

代码覆盖率插件

安装代码覆盖率插件karma-coverage

1
~ D:\workspace\javascript\karma>npm install karma-coverage

修改karma.conf.js配置文件

1
2
3
4
5
6
reporters: ['progress','coverage'],
preprocessors : {'src.js': 'coverage'},
coverageReporter: {
type : 'html',
dir : 'coverage/'
}

启动karma start,在工程目录下面找到index.html文件,coverage/chrome/index.html
打开后,咱们看到代码测试覆率绿报告


覆盖率是100%,说明咱们完整了测试了src.js的功能。

 

接下来,咱们修改src.js,增长一个if分支

1
2
3
4
function reverse(name){
if(name=='AAA') return "BBB";
return name.split("").reverse().join("");
}

再看覆盖率报告,

 

protractor使用介绍

protractor是专为angular应用设计的端到端的测试框架,它直接在浏览器中运行,模拟相似于人在实际环境中的交互操做来测试。

官网主页:http://angular.github.io/protractor/#/

安装使用

执行

1
npm install -g protractor

改命令会安装protractor 和 webdriver-manager两个命令行工具,能够执行

1
protractor --version

来测试是否安装成功。而后经过执行

1
webdriver-manager update

上面的命令会下载必要的支持组建,而后能够经过

1
webdriver-manager start

来启动一个server,咱们运行的protractor test会运行在这个server上,能够在 http://localhost:4444/wd/hub 地址查看server的运行状态。

测试实例

  1. 编写测试脚本,咱们测试angular的官网示例todo list,编写todo-spec.js以下:
1
2
3
4
5
6
7
8
9
10
11
12
describe('angularjs homepage todo list', function() {
it('should add a todo', function() {
browser.get('http://www.angularjs.org');
element(by.model('todoText')).sendKeys('write a protractor test');
element(by.css('[value="add"]')).click();
var todoList = element.all(by.repeater('todo in todos'));
expect(todoList.count()).toEqual(3);
expect(todoList.get(2).getText()).toEqual('write a protractor test');
});
});

其中describe和it使用的是jasmine的语法,browser是protractor提供的全局对象,用于执行浏览器级别的任务,好比导航加载页面能够用browser.get方法。

  1. 编写配置文件conf.js
1
2
3
4
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['todo-spec.js']
};

这个配置文件主要告诉protractor测试的文件和服务器的地址,默认使用chrom浏览器。

  1. 运行测试
1
protractor conf.js

你会看见会自动打开浏览器,跳转到todolist页面,而后关闭页面。

相关文章
相关标签/搜索