3

我最近拿起了 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

非常感谢。

4

2 回答 2

2

这是默认行为吗?

是的。Chai-as-promised 反映了 Chai 所做的事情。当您使用 时expect(fn).to.throw("foo"),Chai 会foo在错误消息中查找子字符串。如果 Chai-as-promised 的工作方式不同,那将是令人困惑的。

如果是,是否有强制错误消息完全匹配的选项?

没有选项可以设置。但是,您可以传递正则表达式而不是字符串。如果你用/^abcde$/错误信息进行测试,则必须完全通过 "abcde"

于 2017-07-21T11:55:39.613 回答
0

要提供使用正则表达式的替代方法,可以执行此操作以强制完全匹配:

it('should fail with an error message "foo".', ()=>{
    return expect(fn).to.eventually.be.rejected.and.has.property('messa‌​ge', 'foo');
});

这是检查被拒绝的对象是否具有属性messagefoo ”。

请注意:这是为了断言从 Promise 中被拒绝/抛出的错误,所以eventually这里是必需的,否则它将无法正常运行。

于 2017-07-24T08:02:56.463 回答