簡體   English   中英

斷言 mocha.js 運行的測試數量

[英]Assert number of tests run by mocha.js

有沒有辦法斷言 mocha 運行的測試數量?
例如:

afterAllTests(() => {
  expect(mocha.numTestsRun).to.be.greaterThan(400);
});

我最近從mocha 7.1.2升級到9.1.3並且-R速記參數停止工作。 我的測試套件從運行 ~400 個測試變成只運行 ~10 個頂級測試。 切換回--recursive解決了這個問題,但我想確保不會再發生這樣的事情。

我的package.json看起來像這樣:

{
  "scripts": {
    "integrationTest": "mocha --recursive spec test/integration",
  }
}

與其計算到目前為止已經運行的測試數量,我會計算已經用 Mocha 聲明的測試數量。 這確保無論執行順序如何,對測試總數的檢查都保持有效。

要計算測試總數,我們需要遞歸計算頂級套件及其所有子套件中聲明的測試數量(沒有捷徑 AFAIK)。

我們首先聲明一個新測試(它可以放在任何地方),其唯一目的是計算測試總數。

在這個測試中,我們可以使用this.runnable().parent來獲取包含套件 反過來,套件還有一個屬性parent ,可用於獲取下一個更高的包含套件,一直到頂級套件(由 Mocha 隱式定義)。 頂級套件的屬性root設置為true

現在,與任何其他套件一樣,頂級套件具有屬性testssuites ,可用於分支所有后代套件並計算聲明的測試總數。

it('total number of tests should be > 400', function() { // Use `function()`, don't use `() =>`...

    let suite0 = this.runnable().parent; // ...because we need to access `this`.
    while (!suite0.root) suite0 = suite0.parent;
    // suite0 is now the top-level suite

    // Recursiveliy count the number of tests in each suite
    const countTests = (cnt, suite) => suite.suites.reduce(countTests, cnt + suite.tests.length);
    const totalTests = countTests(0, suite0);

    expect(totalTests).to.be.greaterThan(400);

});

這將計算所有測試,包括標記為skip測試(但我想這就是您想要的)。

還要注意 - 顯然 - 測試計數測試本身只有在您運行 Mocha 時不要忘記包含它時才有效。 將測試邏輯移動到鈎子beforeafter的頂層不會有太大變化,因為這些鈎子與在同一范圍內聲明的測試具有相同的可見性。 您可以將該測試放在spec文件夾內的文件中,因此即使沒有--recursive標志也會執行它。 作為最后的手段,您可以在環境變量中設置測試數量並在 Mocha 之外檢查該值。

暫無
暫無

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

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