我找不到用Mocha和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);
});
我希望测试能够通过,但是我尝试过的代码失败,提示'错误:抛出了字符串“无效日期”,抛出了错误:)'
答案 0 :(得分:1)
最终的解决方案是定义一个包装函数,该函数调用要测试的函数,然后将包装传递给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);
});
答案 1 :(得分:0)
我相信您应该抛出错误而不是字符串
function SimpleDate(year, month, day) {
if (!isValidDate(year, month, day)) {
throw new Error('invalid date');
}
}