测试这类函数必须等到 promise 对象变成已完成或者失败状态,
mocha 的异步测试有两种方式
- 1.接收 done 参数,该参数表示测试结束;
- 2.测试返回 一个 promise 对象表示最后的测试已经结束
第一种方式可用于测试使用回调的异步函数和返回的promise 对象的函数,
第二种方式显然是针对返回 promise 的函数;
除了使用 mocha, chai ,还用到 chai-as-promised 包;
npm i --save-dev fs-promise chai-as-promised
fs-promise 模块: 和 fs 模块功能相同,但它返回 promise 对象,而不是接收回调函数;
- 参考 async-test 项目,开始测试
# 修改 file.js
let fs = require('fs-promise');
let linesCount = function(fileName){
let onSuccess = function(data){
return Promise.resolve(data.toString().split('\n').length);
};
let onError = function(err){
return Promise.reject(new Error('unable to open file ' + fileName));
}
return fs.readFile(fileName)
.then(onSuccess)
.catch(onError);
}
module.exports = linesCount;
- 修改 file_test.js
var expect = require('chai').expect;
var linesCount = require('../src/file.js');
describe('async test1',function(){
it('shoud pass this canary test',function(){
expect(true).to.eql(true);
});
it('shoud return the correct lines count',function(done){
let callback = function(count){
expect(count).to.be.eql(18);
done();
}
linesCount('src/file.js')
.then(callback);
});
});
- 运行测试
npm test
# 测试通过
如果测试返回的 promise,那么 mocha 就会在宣布测试结束前等着该 promise 对象成为 已完成状态或失败状态,一般都是超时之前,
- 去掉 done() 函数
var expect = require('chai').expect;
var linesCount = require('../src/file.js');
describe('async test1',function(){
it('shoud return the correct lines count',function(){
let callback = function(count){
expect(count).to.be.eql(18);
}
linesCount('src/file.js')
.then(callback);
});
});
- 使用 chai-as-promised 让测试更加简洁
var expect = require('chai').use(require('chai-as-promised')).expect;
var linesCount = require('../src/file.js');
describe('async test1',function(){
it('shoud return the correct lines count',function(){
return expect(linesCount('src/file.js')).to.eventually.eql(18);
});
});
eventually: 实际绑定了一个 promise 对象
- 运行测试
npm test
# 测试通过
- 结合 eventually 和 done()
var expect = require('chai').use(require('chai-as-promised')).expect;
var linesCount = require('../src/file.js');
describe('async test1',function(){
it('shoud return the correct lines count',function(done){
expect(linesCount('src/file.js')).to.eventually.eql(18).notify(done);
});
});
- 反向测试: 传入错误文件名
('src/files.js')
var expect = require('chai').use(require('chai-as-promised')).expect;
var linesCount = require('../src/file.js');
describe('async test1',function(){
it('shoud return the correct lines count',function(done){
expect(linesCount('src/files.js')).to.be.rejected.notify(done);
});
});
- 验证传递正确的错误信息,rejectedWith()
var expect = require('chai').use(require('chai-as-promised')).expect;
var linesCount = require('../src/file.js');
describe('async test1',function(){
it('shoud return the correct lines count',function(done){
expect(linesCount('src/files.js')).to.be.rejectedWith('unable to open file src/files.js').notify(done);
});
});