Asymmetric matchers
03 02 Problem (π solution)
To expose my
.toMatchSchema() matcher as an asymmetric matcher, I need to... do nothing! Vitest automatically provides both symmetric and asymmetric versions for your custom matchers, including type definitions.All that's left for me to do is to use the asymmetric version of the
toMatchSchema() matcher in tests:import { fetchUser } from './fetch-user'
import { userSchema } from './schemas'
test('returns the user by id', async () => {
const user = await fetchUser('abc-123')
expect(user).toEqual(expect.toMatchSchema(userSchema)) // β
})
And in
src/fetch-transaction.test.ts, I will write the remaining test:import { fetchTransaction, type Transaction } from './fetch-transaction'
import { userSchema } from './schemas'
test('fetches a transaction between two users', async () => {
const transaction = await fetchTransaction('transaction-1')
expect(transaction).toEqual<Transaction>({
id: 'transaction-1',
issuer: expect.toMatchSchema(userSchema),
recipient: expect.toMatchSchema(userSchema),
})
})
π¦ Notice the usage of theTransactiontype as the type argument to the default.toEqualmatcher. It ensures that the expected value I pass to that matcher is type-safe.