跳至內容

jest/no-conditional-expect 正確性

作用

此規則會防止在條件區塊 (例如 ifs 和 catch(s)) 中使用 expect。這包括在名為 catch 的函式的回呼中使用 expect,這些函式被假定為 promise。

為何這樣不好?

Jest 只會在測試拋出錯誤時才認為測試失敗,這意味著如果對斷言函式 (如 expect) 的呼叫發生在條件程式碼 (如 catch 語句) 中,測試可能會最終通過,但實際上沒有測試任何內容。此外,條件語句往往會使測試更加脆弱和複雜,因為它們會增加理解實際測試內容所需的心理思考量。

範例

javascript
it("foo", () => {
  doTest && expect(1).toBe(2);
});

it("bar", () => {
  if (!skipTest) {
    expect(1).toEqual(2);
  }
});

it("throws an error", async () => {
  await foo().catch((error) => expect(error).toBeInstanceOf(error));
});

此規則與 eslint-plugin-vitest 相容,若要使用它,請將以下組態加入您的 .eslintrc.json

json
{
  "rules": {
    "vitest/no-conditional-expect": "error"
  }
}

參考資料

以 MIT 授權釋出。