[英]How to expect throw with Mocha and Chai?
我無法找到一種解決辦法來捕獲與摩卡和柴的拋出的字符串
正在測試的代碼:
function SimpleDate(year, month, day) {
if (!isValidDate(year, month, day)) {
throw "invalid date";
}
}
測試代碼:
it("returns 'invalid date' for year = 2023, month = 13, day = 55", function () {
let actual = new DateUtils.SimpleDate(2013, 13, 55);
//let expected ='invalid date';
let expected = expect(() => DateUtils.SimpleDate(2013, 13, 55)).to.throw('invalid date');
assert.equal(actual, expected);
});
我希望測試能夠通過,但是我嘗試過的代碼失敗,提示“錯誤:引發了字符串“無效日期”,引發了錯誤:)”
事實證明,解決方案是定義一個包裝函數,該包裝函數調用要測試的函數,然后將包裝傳遞給assert.throws
it("returns 'invalid date' for year = 2023, month = 13, day = 55", function () {
let year = 2013,
month = 13,
day = 55;
let expectedMessage = 'invalid date';
let wrapper = function () {
let x = DateUtils.SimpleDate(year, month, day);
}
assert.throws(wrapper, expectedMessage);
});
我相信你應該拋出一個錯誤而不是一個字符串
function SimpleDate(year, month, day) {
if (!isValidDate(year, month, day)) {
throw new Error('invalid date');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.