[英]Testing 'throw' with mocha and chai
在我的 function 中,我使用:
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 次失败
这是因为assert.throws
第一个参数采用 function定义,而不是 function结果。 它调用传递的 function 本身。 在您的示例中,您调用的是 function 因此您传递的是 function 结果。
而不是这个:
assert.throws(myFunc(), output)
像这样做:
assert.throws(myFunc, output)
If you want to pass parameters to the function under test, you'll need to wrap it in another unnamed function or use Function.bind to bind some arguments to it.
这是一个工作示例:
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.