[英]How to expect throw with Mocha and Chai?
I am unable to find a solution to catching a thrown string with Mocha and Chai 我无法找到一种解决办法来捕获与摩卡和柴的抛出的字符串
Code being tested: 正在测试的代码:
function SimpleDate(year, month, day) {
if (!isValidDate(year, month, day)) {
throw "invalid date";
}
}
Test code: 测试代码:
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);
});
I expect the test to pass, but the code I have tried fails saying 'Error: the string "invalid date" was thrown, throw an Error :)' 我希望测试能够通过,但是我尝试过的代码失败,提示“错误:引发了字符串“无效日期”,引发了错误:)”
Turns out the solution is to define a wrapper function that calls the function you are testing, and then pass the wrapper to assert.throws 事实证明,解决方案是定义一个包装函数,该包装函数调用要测试的函数,然后将包装传递给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);
});
I believe you should throw an error rather than a string 我相信你应该抛出一个错误而不是一个字符串
function SimpleDate(year, month, day) {
if (!isValidDate(year, month, day)) {
throw new Error('invalid date');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.