如何使用Mocha单元测试errorException?

时间:2019-09-18 08:07:27

标签: javascript mocha

假设我具有此功能:

 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 ');
 }}

我正在尝试编写摩卡单元测试:

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测试编写断言以确认引发了异常?

1 个答案:

答案 0 :(得分:2)

您可以绑定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