2016-11-10 90 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

相關問題