jasmine+karma 自动化单元测试
测试的必须性
相信大家都知道测试的必要性,测试先行的概念。不过,写了这么多年的代码,除了之前用java的时候写过一些测试用例,还真的很少写过前端的测试用例,或者做一些自动化测试。感觉做单元测试还是很有必须的,它能帮助你整理思路,换个角度思考问题,发现bug。最近正好研究一下,之前了解到jasmine是做js单元测试的利器,karma是用来自动化运行分析统计单元测试的,结合karma-coverage还能统计代码覆盖率,这么牛的神器,一定要试一试。另外最后会介绍另外一个端到端的测试神器protractor,不过目前只能测试angular的应用。
转载请注明出处:http://www.haomou.net/2015/03/10/2015_karma_jasmine/
karma安装及使用
Karma是Testacular的新名字,在2012年google开源了Testacular,2013年Testacular改名为Karma。Karma是一个让人感到非常神秘的名字,表示佛教中的缘分,因果报应,比Cassandra这种名字更让人猜不透!
Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其他代码编辑器一起使用。这个测试工具的一个强大特性就是,它可以监控(Watch)文件的变化,然后自行执行,通过console.log显示测试结果。
官网:https://karma-runner.github.io
安装karma
安装nodejs,注意相关版本要求
安装karma和相关插件,推荐的方法是在项目目录安装karma和相关插件
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中。接着可以运行karma
1
2
|
# Run Karma:
$ ./node_modules/karma/bin/karma start
|
注意,直接运行karma是不行的,肯定会报错,需要用上面的方法运行。如果想直接用karma命令,需要安装karma-cli,如下所示:
1
|
$ npm install -g karma-cli
|
然后你就可以直接运行karma命令了。
我们执行
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的项目写单元测试。
使用文档api介绍:http://jasmine.github.io/2.0/introduction.html
运行示例
我们假设在当前目录,按照上面的方法安装了karma,(需要注意的是上面安装karma的时候已经安装了jasmine),然后我们做个测试。
- 编写源文件src.js
1
2
3
|
function reverse(name){
return name.split("").reverse().join("");
}
|
- 编写测试代码test.js
1
2
3
4
5
|
describe("A suite of basic functions", function() {
it("reverse word",function(){
expect("DCBA").toEqual(reverse("ABCD"));
});
});
|
- 修改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
});
};
|
刚才通过命令行的方式生成的配置文件和上面的可能有所不同,作参考。
- 启动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的运行状态。
测试实例
- 编写测试脚本,我们测试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方法。
- 编写配置文件conf.js
1
2
3
4
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['todo-spec.js']
};
|
这个配置文件主要告诉protractor测试的文件和服务器的地址,默认使用chrom浏览器。
- 运行测试
1
|
protractor conf.js
|
你会看见会自动打开浏览器,跳转到todolist页面,然后关闭页面。
最新文章
- Java中将0x开头的十六进制字符串转换成十进制整数
- error CS0016: 未能写入输出文件
- .NET性能调优之一:ANTS Performance Profiler的使用
- 1029 C语言文法
- 【转】为什么我要用 Node.js? 案例逐一介绍
- axure变量的使用
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 慕课网-安卓工程师初养成-4-12 Java循环跳转语句之 continue
- Linux内存管理原理 与文件读写 图 相当详细
- I/O输出端口照明LED
- Android第二天
- nginx系列12:一致性哈希算法
- Vue 中动态添加class(使用v-bind:class)
- 数据库编程Case when
- nginx ssl 自签证书实验
- 【2016.3.22】作业 Word count 小程序
- PPPOE
- iis重启的几种方法
- vue--自定义验证指令
- android 打开系统相机,