擴展匹配器
由於 Vitest 與 Chai 和 Jest 相容,您可以使用 chai.use
API 或 expect.extend
。
本指南將介紹如何使用 expect.extend
擴展匹配器。如果您對 Chai 的 API 感興趣,請查看他們的指南。
若要擴充預設的匹配器,請呼叫 expect.extend
並傳入包含您的匹配器的物件。
expect.extend({
toBeFoo(received, expected) {
const { isNot } = this;
return {
// 不要根據 isNot 更改您的 "pass"。Vitest 會為您處理
pass: received === 'foo',
message: () => `${received} is${isNot ? ' not' : ''} foo`,
};
},
});
若您使用 TypeScript,自 Vitest 0.31.0 起,您可以使用以下程式碼,在全域宣告檔案 (例如:vitest.d.ts
) 中擴展預設的 Assertion
介面。
import type { Assertion, AsymmetricMatchersContaining } from 'vitest';
interface CustomMatchers<R = unknown> {
toBeFoo: () => R;
}
declare module 'vitest' {
interface Assertion<T = any> extends CustomMatchers<T> {}
interface AsymmetricMatchersContaining extends CustomMatchers {}
}
WARNING
請記得在您的 tsconfig.json
中包含全域宣告檔案。
匹配器的回傳值需符合以下介面:
interface MatcherResult {
pass: boolean;
message: () => string;
// 如果您傳遞這些,它們將在 matcher 未通過時自動出現在差異中,因此您無需自己列印差異
actual?: unknown;
expected?: unknown;
}
WARNING
如果您建立非同步匹配器,請記得在測試中使用 await
來獲取結果 (await expect('foo').toBeFoo()
)。
匹配器函數的第一個參數是接收到的值(即 expect(received)
中的 received
值)。其餘參數則會直接傳遞給匹配器。
匹配器函數可以存取包含以下屬性的 this
上下文:
isNot
若匹配器透過
not
呼叫,則返回 true (expect(received).not.toBeFoo()
)。promise
若匹配器透過
resolved/rejected
呼叫,此值會包含修飾符的名稱。否則,它將是一個空字串。equals
此為一實用函數,可讓您比較兩個值。如果值相等,則傳回
true
,否則傳回false
。此函數在內部用於幾乎每個匹配器。它預設支援具有非對稱 matchers 的物件。utils
內含一組實用函數,可用於顯示訊息。
this
上下文亦包含當前測試的相關資訊。您亦可透過呼叫 expect.getState()
來取得它。最有用的屬性是:
currentTestName
當前測試的完整名稱(包括 describe 區塊)。
testPath
當前測試的路徑。