admin管理员组文章数量:1291026
I'm confused looking at the documention how we should test the error.
I have this divide function in 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;
}
}
How should the test look like? I know it gonna be 2 case, the first one is to test the divide, I have no problem with it, but I have no clue how to test the error if user pass zero.
I'm using mocha and assert (node's assert)
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', () => {
})
})
I'm confused looking at the documention how we should test the error.
I have this divide function in 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;
}
}
How should the test look like? I know it gonna be 2 case, the first one is to test the divide, I have no problem with it, but I have no clue how to test the error if user pass zero.
I'm using mocha and assert (node's assert)
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', () => {
})
})
Share
Improve this question
asked Feb 17, 2018 at 12:34
Chuang yeChuang ye
651 gold badge1 silver badge3 bronze badges
1
-
1
assert.throws
ortry/catch
withassert
true/false (true in catch block). – Egor Stambakio Commented Feb 17, 2018 at 12:37
1 Answer
Reset to default 7The implementation code would look like this:
divide(dividend, divisor) {
if (divisor === 0) {
throw new Error('the quotient of a number and 0 is undefined');
} else {
return dividend / divisor;
}
},
The test code would look like this:
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);
})
This is according to the nodejs documentation
本文标签: javascripttest error thrown using assert of nodejsStack Overflow
版权声明:本文标题:javascript - test error thrown using assert of node.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741511789a2382648.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论