หัวข้อ | คำอธิบาย |
---|---|
ความสามารถของ Vitest | รองรับทั้ง Chai และ Jest |
วิธีการขยาย matchers | สามารถใช้ได้ทั้ง chai.use API และ expect.extend |
เนื้อหาของคำแนะนำนี้ | เน้นการใช้ expect.extend |
สำหรับผู้สนใจ Chai API | แนะนำให้ดูคู่มือของ Chai โดยตรง |
วิธีการขยาย default matchers | ใช้ expect.extend โดยส่ง object ที่มี matchers ที่ต้องการเพิ่ม |
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`
}
}
})
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 {}
}