我对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带有错误邮政编码的请求会引发错误:错误:INVALID_POSTCODE
似乎抛出的错误导致测试失败,但我不太确定。有没有人有任何想法?
答案 0 :(得分:6)
有一点需要注意,我不是柴的专家,你有这样的结构:
expect(subject.formatPostcodeStatus(status)).to.throw(Error);
在Chai框架看到你的.to.throw()
链之前,无法处理抛出的异常。上面的代码在调用expect()
之前调用函数,因此异常发生得太快。
相反,您应该将函数传递给expect()
:
expect(function() { subject.formatPostCodeStatus(status); })
.to.throw(Error);
这样,框架可以在为准备异常后调用函数。