【问题标题】:How can I use rejectedWith to perform an exact match of the error message?如何使用rejectWith 来执行错误消息的完全匹配?
【发布时间】:2017-07-21 00:59:58
【问题描述】:

我最近选择了 JS 单元测试库 Mocha、Chai 和 Chai-As-Promise。但是,我遇到了一种情况,我不确定这是默认行为还是我错过了。

当我断言一个被 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');
    });
});

这是默认行为吗?如果是,是否有强制错误消息完全匹配的选项?

摩卡@3.4.2 柴@4.0.2 chai-as-promised@7.1.1 q@1.5.0

非常感谢。

【问题讨论】:

    标签: javascript unit-testing mocha.js chai chai-as-promised


    【解决方案1】:

    这是默认行为吗?

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

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

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

    【讨论】:

    • 谢谢,起初我无法将“rejectedWith”与“throw”联系起来,所以我找不到正确的信息。但现在它是有道理的 :) 如果有人停下来有同样的奇迹,这里是文档的链接:[chaijs.com/api/assert/#method_throws] 注意:我的一个朋友向我展示了一个同样有效的替代方案:expect(fn).to.eventually.be.rejected.and.has.property('message', 'foo');
    • 啊,是的,这也有效。无论如何,我经常使用正则表达式,所以我已经使用rejectedWith 进行了管理,并且我没有寻求另一种方法来做到这一点。您可以将其作为另一个答案提交。
    【解决方案2】:

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

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

    即检查被拒绝的对象是否有属性message"foo"。

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

    【讨论】:

    • 另外请注意,这里需要在expect之前“return”或“await”,否则总会通过。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2020-10-08
    相关资源
    最近更新 更多