我很困惑地看着文档如何测试错误。
我在index.js中有这个除法函数
function divide(dividend, divisor) {
if(divisor === 0) {
throw new Error('the quotient of a number and 0 is undefined');
} else {
return dividend / divisor;
}
}
测试应该如何?我知道这将是2个案例,第一个是测试鸿沟,我没有问题,但我不知道如果用户传递零,如何测试错误。
我使用mocha和断言(节点断言)
describe('.divide', () => {
it('returns the first number divided by the second number', () => {
assert.equal(5, Calculate.divide(10,2))
})
it('throws an error when the divisor is 0', () => {
})
})
答案 0 :(得分:1)
实现代码如下所示:
divide(dividend, divisor) {
if (divisor === 0) {
throw new Error('the quotient of a number and 0 is undefined');
} else {
return dividend / divisor;
}
},
测试代码如下所示:
it("returns an exception when the divisor is 0", () => {
const dividend = 8;
const divisor = 0;
expected = Error;
const exercise = () => Calculate.divide(dividend, divisor);
assert.throws(exercise, expected);
})
这是根据nodejs documentation