我对我们应该如何测试错误的文档感到困惑。
我在 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 和断言( Node 的断言)
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', () => {
})
})
最佳答案
实现代码如下所示:
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
关于javascript - 使用 node.js 的断言引发的测试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841325/