簡體   English   中英

用Chai.js測試失敗

[英]Fail a test with Chai.js

在JUnit中,您可以通過執行以下操作來使測試失敗:

fail("Exception not thrown");

使用Chai.js實現相同目標的最佳方法是什么?

assert.fail() 你可以像這樣使用它:

assert.fail(0, 1, 'Exception not thrown');

偽造失敗的方法有很多 - 比如assert.fail()提到的assert.fail() ,但通常可以避免這些拐杖並以更好的方式表達測試的意圖,這將導致更有意義的測試失敗時的消息。

例如,如果您希望拋出異常,為什么不直接這樣說:

expect( function () {
    // do stuff here which you expect to throw an exception
} ).to.throw( Error );

如您所見,在測試異常時,您必須將代碼包裝在匿名函數中。

當然,您可以通過檢查更具體的錯誤類型,預期的錯誤消息等來優化測試。請參閱Chai文檔中的 .throw以獲取更多信息。

我也發現這里沒有直接fail(msg) 一段時間以來,我一直在努力......

assert.isOk(false, 'timeOut must throw')

(在無法訪問的地方使用此功能,即在承諾測試中......)

Chai與標准的ES6錯誤兼容,因此這有效:

throw new Error('timeOut must throw') 

...或者,因為斷言本身與assert.isOK基本相同 ......我最喜歡的是:

assert(false,'timeOut must throw')

......好吧,幾乎和assert.fail(…一樣短assert.fail(…

試一試

expect.fail("custom error message");

要么

should.fail("custom error message");

如chai docs所述: https//www.chaijs.com/api/bdd/#method_fail

我這樣做了

const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');

暫無
暫無

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

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