跳到內容

擴充比對器

由於 Vitest 與 Chai 和 Jest 相容,你可以使用 chai.use API 或 expect.extend,任你選擇。

本指南將探討使用 expect.extend 擴充比對器。如果你對 Chai 的 API 感興趣,請查看 他們的指南

若要擴充預設比對器,請使用包含比對器的物件呼叫 expect.extend

ts
expect.extend({
  toBeFoo(received, expected) {
    const { isNot } = this
    return {
      // do not alter your "pass" based on isNot. Vitest does it for you
      pass: received === 'foo',
      message: () => `${received} is${isNot ? ' not' : ''} foo`
    }
  }
})

如果你使用 TypeScript,由於 Vitest 0.31.0,你可以使用以下程式碼在環境宣告檔案 (例如:vitest.d.ts) 中擴充預設 Assertion 介面

ts
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 {}
}

警告

別忘了在 tsconfig.json 中包含環境宣告檔案。

比對器的回傳值應與下列介面相容

ts
interface MatcherResult {
  pass: boolean
  message: () => string
  // If you pass these, they will automatically appear inside a diff when
  // the matcher does not pass, so you don't need to print the diff yourself
  actual?: unknown
  expected?: unknown
}

警告

如果您建立非同步比對器,請別忘記在測試中await結果(await expect('foo').toBeFoo())。

比對器函式內的第 1 個引數是接收到的值(expect(received) 內的值)。其餘引數會直接傳遞給比對器。

比對器函式可以存取具有下列屬性的this內容

  • isNot

    如果比對器是在not中呼叫的(expect(received).not.toBeFoo()),則傳回 true。

  • promise

    如果比對器是在resolved/rejected中呼叫的,則此值會包含修改項的名稱。否則,它會是空字串。

  • equals

    這是一個允許您比較兩個值之公用函式。如果值相等,它會傳回true,否則傳回false。此函式在內部用於幾乎每個比對器。它預設支援具有非對稱比對器的物件。

  • utils

    此處包含一組您可以用來顯示訊息的公用函式。

this內容也包含有關目前測試的資訊。您也可以透過呼叫expect.getState()來取得它。最實用的屬性為

  • currentTestName

    目前測試的完整名稱(包含 describe 區塊)。

  • testPath

    目前測試的路徑。