我正在尝试在 Vitest 中创建一个 Expect.extend,我尝试遵循 文档
我创建了一个 vitest.d.ts 文件,并在其中声明:
interface CustomMatchers<R = unknown> {
toPassGuard(guardFunc: (record: unknown) => boolean): boolean;
toPassGuardArray<T = unknown>(guardFunc: (record: T) => boolean): boolean;
}
declare module 'vitest' {
interface Assertion<T = any> extends CustomMatchers<T> {}
interface AsymmetricMatchersContaining extends CustomMatchers {}
}
我仍然在这里遇到类型错误
expect(arrOfSettings).toPassGuardArray(isSettings)
Property 'toPassGuardArray' does not exist on type 'Assertion<string| undefined>[], any>'
我找到了一个解决方法,将 Assertion 更改为 JestAssertion (这是一个子包) ,这有效,但前提是匹配器定义位于我使用它的同一个文件中,
示例:
expect.extend({
toPassGuardArray(received, guardFunc) {
const failedItems = received.filter((receiveItem) => !guardFunc(receiveItem))
const pass = failedItems.length === 0
return {
pass,
message: () => `${failedItems.length} did${!pass ? ' not' : ''} pass guard ${guardFunc.name}`,
actual: (`${failedItems.map((item) => item)} to pass guard`).substring(0, 300)
}
}
})
现在这个
expect(allEnriched).toPassGuardArray<Asset>(guard)
仅当 Expect.extend 位于同一文件中时才有效,否则我会得到
Error: Invalid Chai property: toPassGuardArray
Chai 也是一个子包,所以我猜这里存在冲突......
好吧,我明白了,我应该将所有自定义断言包含到安装文件中, 并将其添加到配置中
export default defineConfig({
test: {
setupFiles: ['filesWhereIDeclare.js'],
},
});