2016-11-10 61 views
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

好像正被抛出的错误导致测试失败,但我不太确定。有没有人有任何想法?

回答

4

随着那我不是柴专家告诫,你有结构:

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

没法处理抛出的异常的柴框架得到周围看到您的.to.throw()链之前。上述该代码调用调用expect()由前的功能,所以异常太早发生。

相反,你应该通过一个函数来expect()

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

这样一来,该框架可调用函数后,它的例外准备。

+0

当然!所有工作如预期现在。感谢您提供丰富的答案和代码片段;我明白为什么发生这个问题,并且您的解决方案完美运行。 – tombraider