【问题标题】:Testing 'throw' with mocha and chai用 mocha 和 chai 测试“投掷”
【发布时间】:2020-07-27 07:31:08
【问题描述】:
在我的函数中我使用:
if (apples === undefined) {
throw new Error('Error');
}
在我的测试中,我试图通过以下方式确认这是有效的:
it('throw an error if apples is undefined', function() {
const input = undefined;
const output = "Error";
assert.throws(myFunc(input), output);
});
但是我得到:
1 次失败
- myFunc
如果 apples 未定义,应该抛出错误:
错误
错误
【问题讨论】:
标签:
javascript
mocha.js
chai
【解决方案1】:
这是因为assert.throws 第一个参数采用函数定义,而不是函数result。它调用传递的函数本身。在您的示例中,您正在调用函数,因此您正在传递函数结果。
而不是这个:
assert.throws(myFunc(), output)
这样做:
assert.throws(myFunc, output)
如果要将参数传递给被测函数,则需要将其包装在另一个未命名的函数中或使用Function.bind 为其绑定一些参数。
这是一个工作示例:
const assert = require("assert")
function myFunc(apples) {
if (!apples) {
throw new Error("Apples must have a non-null value");
}
return apples + " are good";
}
describe("myFunc", () => {
it("throws an error if apples is undefined", function() {
const input = undefined;
const output = new Error("Error");
assert.throws(function() {
myFunc(input);
}, output);
})
})
请注意,您还需要测试它是否抛出了 Error 的实例而不是 String。