gpt4 book ai didi

javascript - 如何使用 mocha 对 errorexception 进行单元测试?

转载 作者:行者123 更新时间:2023-11-30 13:52:26 24 4
gpt4 key购买 nike

假设我有这个功能:

 try
{
if (s1 <0 || s2<0 ||s3 <0){
throw new Error('InvalidTriangleExeption ');
}
let s = (s1 + s2 + s3)/2;
var area = Math.sqrt(s*((s-s1)*(s-s2)*(s-s3)));
return area;
}
catch{
throw new Error('InvalidTriangleExeption ');
}}

我正在尝试编写 mocha 单元测试:

expect( question3(-1,4,5)).to.throw('InvalidTriangleExeption')

但我的测试因错误而崩溃:

 Error: InvalidTriangleExeption 
at go (src/questions/question3.js:13:15)
at Context.<anonymous> (tests/question3.spec.js:14:13)

我如何为 mocha 测试编写断言以确认抛出异常?

最佳答案

你可以绑定(bind)args来解决这个问题

expect(question3.bind(this, -1, 5, 4)).to.throw(); // PASS
expect(question3.bind(this, -1, 5, 4)).to.throw('InvalidTriangleExeption'); // PASS
expect(question3.bind(this, -1, 5, 4)).to.throw('ABCExeption'); // FAIL

expect(question3.bind(this, -1, 5, 4)).to.not.throw('InvalidTriangleExeption'); // FAIL
expect(question3.bind(this, -1, 5, 4)).to.not.throw('ABCExeption'); // PASS
expect(question3.bind(this, -1, 5, 4)).to.not.throw(); // FAIL

关于javascript - 如何使用 mocha 对 errorexception 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57987938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com