我对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.";
}
};
Run Code Online (Sandbox Code Playgroud)
我已经设法为消息传递编写测试,但是,我正在努力进行错误测试.这是我迄今为止所写的内容:
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);
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行上面的测试时,我收到以下错误消息:
1)networkDataHelper #formatPostcodeStatus带有错误邮政编码的请求会引发错误:错误:INVALID_POSTCODE
似乎抛出的错误导致测试失败,但我不太确定.有没有人有任何想法?
随着我不是柴专家的警告,你有这样的结构:
expect(subject.formatPostcodeStatus(status)).to.throw(Error);
Run Code Online (Sandbox Code Playgroud)
在Chai框架到处看到你的.to.throw()链之前,不可能处理抛出的异常.上面的代码调用该函数之前的号召expect()制成,所以异常太早发生.
相反,您应该将函数传递给expect():
expect(function() { subject.formatPostCodeStatus(status); })
.to.throw(Error);
Run Code Online (Sandbox Code Playgroud)
这样,框架可以在为异常做好准备后调用该函数.
| 归档时间: |
|
| 查看次数: |
4447 次 |
| 最近记录: |