NadavT
NadavT

Reputation: 113

Vitest expect extend

I'm trying to create an expect.extend in Vitest, I tried following the docs

I created a vitest.d.ts file where I declare this:

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

Still I get a type error here expect(arrOfSettings).toPassGuardArray(isSettings)

Property 'toPassGuardArray' does not exist on type 'Assertion<string| undefined>[], any>'

I found a workaround where I changed Assertion to JestAssertion (which is a sub package) , and this works but only if the matcher definition is in the same file I use it,

example:

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)
    }
  }
})

now this expect(allEnriched).toPassGuardArray<Asset>(guard) only works if expect.extend is in the same file, otherwise I'm getting

Error: Invalid Chai property: toPassGuardArray

Chai is also a sub package so there is a conflict here I guess...

Upvotes: 2

Views: 1240

Answers (1)

NadavT
NadavT

Reputation: 113

Okay I got it, I should have include all custom assertions to a setup file, and add it in the config

export default defineConfig({
  test: {
    setupFiles: ['filesWhereIDeclare.js'],
  },
});

Upvotes: 2

Related Questions