猿问

如何使用 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 ');

 }}

我正在尝试编写一个 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 测试编写断言?


心有法竹
浏览 333回答 1
1回答

眼眸繁星

你可以绑定args来解决这个问题expect(question3.bind(this, -1, 5, 4)).to.throw(); // PASSexpect(question3.bind(this, -1, 5, 4)).to.throw('InvalidTriangleExeption'); // PASSexpect(question3.bind(this, -1, 5, 4)).to.throw('ABCExeption'); // FAILexpect(question3.bind(this, -1, 5, 4)).to.not.throw('InvalidTriangleExeption'); // FAILexpect(question3.bind(this, -1, 5, 4)).to.not.throw('ABCExeption'); // PASSexpect(question3.bind(this, -1, 5, 4)).to.not.throw(); // FAIL
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答