【问题标题】:Chai - expect function to throw error [duplicate]Chai - 期望函数抛出错误[重复]
【发布时间】:2017-03-24 14:37:45
【问题描述】:

我对 Chai 还很陌生,所以我还在掌握一些东西。

我编写了一个函数来检查 API 响应并返回正确的消息或抛出错误。

networkDataHelper.prototype.formatPostcodeStatus = function(postcodeStatus) {

if (postcodeStatus.hasOwnProperty("errorCode")) {
    //errorCode should always be "INVALID_POSTCODE"
    throw Error(postcodeStatus.errorCode);
}

if (postcodeStatus.hasOwnProperty("lori")) {
    return "There appears to be a problem in your area. " + postcodeStatus.lori.message;
}

else if (postcodeStatus.maintenance !== null) {
    return postcodeStatus.maintenance.bodytext;
}

else {
    return "There are currently no outages in your area.";
}
};

我已经设法为消息传递编写测试,但是,我正在为错误测试而苦苦挣扎。以下是我迄今为止所写的内容:

var networkDataHelper = require('../network_data_helper.js');

describe('networkDataHelper', function() {
var subject = new networkDataHelper();
var postcode;

    describe('#formatPostcodeStatus', function() {
        var status = {
            "locationValue":"SL66DY",
            "error":false,
            "maintenance":null,
        };

        context('a request with an incorrect postcode', function() {
            it('throws an error', function() {
                status.errorCode = "INVALID_POSTCODE";
                expect(subject.formatPostcodeStatus(status)).to.throw(Error);
            });
        });
    });
});

当我运行上面的测试时,我收到以下错误消息:

1) networkDataHelper #formatPostcodeStatus 带有不正确邮政编码的请求会引发错误:Error: INVALID_POSTCODE

似乎抛出的错误导致测试失败,但我不太确定。有人有什么想法吗?

【问题讨论】:

    标签: javascript chai


    【解决方案1】:

    请注意,我不是 Chai 专家,您的构造:

    expect(subject.formatPostcodeStatus(status)).to.throw(Error);
    

    在 Chai 框架看到你的.to.throw() 链之前,不可能处理抛出的异常。上面的代码调用函数调用expect()之前,所以异常发生得太快了。

    相反,您应该将一个函数传递给expect()

    expect(function() { subject.formatPostCodeStatus(status); })
      .to.throw(Error);
    

    这样,框架可以在为异常做好准备后调用函数。

    【讨论】:

    • 当然!现在一切都按预期工作。感谢您提供信息丰富的答案和代码 sn-p;我了解问题发生的原因,并且您的解决方案运行良好。
    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 2015-05-10
    • 2017-12-06
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多