Asymmetric matchers

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 the Transaction type as the type argument to the default .toEqual matcher. It ensures that the expected value I pass to that matcher is type-safe.

Please set the playground first

Loading "Asymmetric matchers"
Loading "Asymmetric matchers"

Access Denied

You must login or register for the workshop to view and run the tests.

Check out this video to see how the test tab works.