适用范围:
1. 运行环境
梗概:
- 一个前端自动化测试框架
- 国内关于该测试框架的详解文章非常少, 质量也低
示例
安装和配置
安装mocha:
npm install mocha --save-dev
配置package.json:
"scripts": {
"test": "mocha"
}
安装chai和sinon:
npm install chai sinon --save-dev
配置babel和istanbul:
npm install @babel/core @babel/register @babel/preset-env istanbul-lib-instrument --save-dev
创建.babelrc文件:
{
"presets": ["@babel/preset-env"]
}
创建.mocha.opts文件:
--recursive ./test/*.js
--require @babel/register
--reporter spec
nyc --require babel-register mocha --reporter spec ./test/*.spec.js"
}
编写测试用例
const { expect } = require('chai');
const sinon = require('sinon');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
expect([1, 2, 3].indexOf(4)).to.equal(-1);
});
});
});
describe('Sinon', function() {
describe('#stub()', function() {
it('should stub a method and return a fake value', function() {
const obj = { method: () => 'original' };
const stub = sinon.stub(obj, 'method').returns('stubbed');
expect(obj.method()).to.equal('stubbed');
stub.restore();
});
});
});
运行测试用例
npm test
查看覆盖率报告
npm run coverage