2
我对柴很新,所以我仍然在处理事情。柴 - 期望函数抛出错误
我写了函数来检查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 a request with an incorrect postcode throws an error: Error: INVALID_POSTCODE
好像正被抛出的错误导致测试失败,但我不太确定。有没有人有任何想法?
当然!所有工作如预期现在。感谢您提供丰富的答案和代码片段;我明白为什么发生这个问题,并且您的解决方案完美运行。 – tombraider