@H_301_1@单元测试专门用于测试小型、独立的代码单元,单个函数,或者较小的功能,其主要难点在于划分小的功能块。
@H_301_1@本位主要介绍AngularJS的单元测试的环境搭建。
test.spec.js
创建测试配置文件
@H_301_1@代码覆盖率(test/coverage/index.html)
Karma是一个基于Node.js的JavaScript测试执行过程管理工具(Test Runner)。该工具可用于测试所有主流Web浏览器,也可集成到CI(Continuous integration)工具,也可和其他代码编辑器一起使用。
Jasmine (茉莉)是一款 JavaScript BDD(行为驱动开发)测试框架,它不依赖于其他任何 JavaScript 组件。它有干净清晰的语法,让您可以很简单的写出测试代码。对基于 JavaScript 的开发来说,它是一款不错的测试框架选择。
@H_301_1@ npmmakes 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.
项目文件结构
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(测试框架)(npminstall -gjasmine-core)
- What is npm?
- 代码覆盖率
You can use(npm init)in the root of your package in order to get you started with a pretty basic package.jsonfile.
项目文件结构
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 starttest/karma.conf.js
Reporter that dynamically shows tests results at debug.html page.
安装:
@H_301_1@npminstallkarma-jasmine-html-reporter-g
修改
karma.conf.js相应部分:
@H_301_1@reporters:['progress','coverage','kjhtml'] 启动测试:
karma starttest/karma.conf.js