我最近拿起了 JS 单元测试库 Mocha、Chai 和 Chai-As-Promise。但是,我遇到了一种情况,我不确定这是默认行为还是我错过了。
当我断言从承诺中拒绝的错误消息时,似乎只要预期的错误消息是实际错误消息的子字符串,它的断言就会通过。下面是一个例子:
var chai = require('chai');
var expect = chai.expect;
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var q = require('q');
describe('demo test', function(){
// a mock up promise function for demo purpose
function test(input){
var d = q.defer();
setTimeout(function() {
if(input){
d.resolve('12345');
}else{
// throw a new Error after half a sec here
d.reject(new Error('abcde fghij'));
}
}, (500));
return d.promise;
}
// assertion starts here
it('should pass if input is true', ()=>{
return expect(test(true)).to.eventually.equal('12345');
});
it('this passes when matching the first half', ()=>{
return expect(test(false)).to.be.rejectedWith('abcde');
});
it('this also passes when matching the second half', ()=>{
return expect(test(false)).to.be.rejectedWith('fghij');
});
it('this again passes when even only matching the middle', ()=>{
return expect(test(false)).to.be.rejectedWith('de fg');
});
it('this fails when the expected string is not a substring of the actual string', ()=>{
return expect(test(false)).to.be.rejectedWith('abcdefghij');
});
});
这是默认行为吗?如果是,是否有强制错误消息完全匹配的选项?
mocha@3.4.2 chai@4.0.2 chai-as-promised@7.1.1 q@1.5.0
非常感谢。