簡體   English   中英

如何使用Mocha單元測試errorException?

[英]How to unit test an errorexception with 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測試的斷言?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM