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