应该先了解最核心的断言模块/库,而后结合现有的测试框架和管理工具进行开发测试用例。javascript
所谓"断言",就是判断源码的实际执行结果与预期结果是否一致,若是不一致就抛出一个错误。 经常使用的断言库有assert、should.js、chai.jshtml
assert.deepStrictEqual(actual,expected[,message])前端
对比actual和expected参数是否深度相等。便可枚举属性也会按照规则比较。java
const assert = require('assert');
let a = {
b: 1
}
let b = {
b: 2
}
assert.deepStrictEqual(a,b,'budui')
复制代码
最关键的是最后一行代码,当比较的两个对象不深度相等时,则Assert抛出错误node
AssertionError [ERR_ASSERTION]: 对象不相等 at Object.git
用法上其实和assert差很少。api相对较多。具体参考官网。github
实际业务测试中,优秀的测试框架必不可少,有Mocha、Jasmine、Tape、jest等ajax
describe('addTest', function () {
it('0.1加上0.2等于0.3', function () {
// 使用should.js断言
add(0.1, 0.2).should.equal(0.3)
})
})
复制代码
Mocha 测试用例如上,主要包含下面几部分:typescript
describe 定义的测试套件(test suite),第一个参数是套件名称,第二个参数是一个函数npm
it 定义的测试用例(test case),第一个参数是用例名称,第二个参数是一个函数。
一个describe里能够有多个it
默认每一个测试用例最多执行2000毫秒,可使用-t参数指定超时时间
mocha -t 5000 test.js
it('should able to request https://api.github.com/', function (done) {
// 使用 jQuery.ajax 请求
$.ajax({
url:"https://api.github.com/",
success: function() {
done()
}
})
})
复制代码
异步测试时,须要在异步完成后加入done()告诉mocha测试结束。不然会一直等待,超时报错。
在describe中调用
mocha还有其余不少功能,如
监视指定测试用例,自动执行(mocha -w)
用例管理(only,skip)
...
只需前往Mocha查看文档
参考: 测试框架 Mocha 实例教程
Which testing framework do you want to use? Press tab to list possible options. Enter to move to the next question.
mocha
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 Firefox
What is the location of your source and test files? You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js". Press Enter to move to the next question.
node_modules/should/should.js test/**/*.js
Should any of the files included by the previous patterns be excluded? You can use glob patterns, eg. "**/*.swp". Press Enter 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
完成后会在项目根目录生成配置文件 karma.conf.js
持续集成指的是只要代码有变动,就自动运行构建和测试,反馈运行结果。
这里我采用了Travis CI
每次提交代码之后会根据配置文件的跑测试用例。不管是否跑通,都会有相应的报告。
参考: