Asymmetric matchers
Loading "03 02 Problem (π solution)"
03 02 Problem (π solution)
Run locally for transcripts
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 theTransaction
type as the type argument to the default.toEqual
matcher. It ensures that the expected value I pass to that matcher is type-safe.