扩展匹配器
由于 Vitest 兼容 Chai 和 Jest,你可以使用 chai.use
API 或 expect.extend
API,选择你喜欢的方式。
本指南将介绍如何使用 expect.extend
扩展匹配器。如果你对 Chai 的 API 感兴趣,请查阅 Chai 官方指南。
要扩展默认匹配器,请使用一个包含自定义匹配器的对象调用 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;
// 如果你传递这些属性,当匹配器失败时,它们会自动出现在 diff 中,
// 因此无需手动输出 diff
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
。此函数在内部被几乎每个匹配器使用。它默认支持带有非对称匹配器的对象。utils
这里包含一组实用函数,你可以使用它们来格式化消息。
this
上下文还包含有关当前测试的信息。你也可以通过调用 expect.getState()
获取这些信息。最有用的属性包括:
currentTestName
当前测试的完整名称(包括所有 describe 块)。
testPath
当前测试文件的路径。