单元测试专门用于测试小型、独立的代码单元,单个函数,或者较小的功能,其主要难点在于划分小的功能块。
本位主要介绍AngularJS的单元测试的环境搭建。
Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其他代码编辑器一起使用。
Jasmine (茉莉)是一款 JavaScript BDD(行为驱动开发)测试框架,它不依赖于其他任何 JavaScript 组件。它有干净清晰的语法,让您可以很简单的写出测试代码。对基于 JavaScript 的开发来说,它是一款不错的测试框架选择。
环境搭建
-
安装NodeJS(JavaScript运行环境)(https://nodejs.org/en/)
-
安装npm(JavaScript包管理工具)(npm is installed with Node.js)
-
安装karma(JavaScript测试运行器)(npm install -g karma)
-
安装jasmine(测试框架)(npm install -g jasmine-core)
-
代码覆盖率统计插件(npm install -g karma-coverage)
npm makes it easy for JavaScript developers to share and reuse code, and makes iteasy to update the code that you're sharing, so you can build amazing things.
如何衡量测试脚本的质量呢?其中一个参考指标就是代码覆盖率(coverage)。
什么是代码覆盖率?简而言之就是测试中运行到的代码占所有代码的比率。
项目配置
You can use( npm init )in the root of your package in order to get you started with a pretty basic package.json file.
项目文件结构
index.js
function isNum(num) {
if (typeof num === 'number') {
return true;
}
else {
return false;
}
}
test.spec.js
describe('index.js: ', function() {
it('isNum() should work fine.', function() {
expect(isNum(1)).toBe(true)
expect(isNum('1')).toBe(false)
})
})
创建测试配置文件
karma init test/karma.conf.js
karma-coverage配置
修改配置文件karma.conf.js
启动单元测试
karma start test/karma.conf.js
注:karma.conf.js中autowatch设置为true时每次代码有变化时,自动运行 单元测试。
代码覆盖率(test/coverage/index.html)
插件:karma-jasmine-html-reporter
Reporter that dynamically shows tests results at debug.html page.
安装:
npm install karma-jasmine-html-reporter -g
修改karma.conf.js相应部分:
reporters:['progress', 'coverage', 'kjhtml']
启动测试:
karma start test/karma.conf.js
启动测试:karma start test/karma.conf.js