---
type: snippet
tags: ['test', 'vitest', 'matchers', 'zod']
status: release
ctime: 2024-09-15
mtime: 2024-09-15
---

[vitest](https://vitest.dev/)에서 사용자 지정 assertion을 추가하여 Zod 스키마와 Response 객체를 비교하기

```ts
import { expect } from 'vitest'
import type { ZodTypeAny } from 'zod'

expect.extend({
  /**
   * @param received 테스트할 Response 객체
   * @param schema 검증할 Zod 스키마
   */
  async toMatchSchema(received: Response, schema: ZodTypeAny) {
    const response = await received.json()
    const result = await schema.safeParseAsync(response)

    return {
      message: () => '',
      pass: result.success,
    } satisfies ExpectationResult
  },
})
```

`vitest.d.ts` 파일에서 CustomMatchers 인터페이스를 확장하여 TypeScript와의 통합성을 유지.

```ts
import type { ZodTypeAny } from 'zod'

interface CustomMatchers<R = unknown> {
  toMatchSchema(schema: ZodTypeAny): Promise<R>
}
```

`todoResponse`의 응답 데이터가 `todoSchema`에 정의된 Zod 스키마와 일치하는지 확인한다.

```ts
test('todo', async () => {
  expect(todoResponse.ok).toBeTruthy()
  expect(todoResponse).toMatchSchema(todoSchema)
})
```

---

- [Extending Matchers | Guide | Vitest](https://vitest.dev/guide/extending-matchers)
- [Expect · Jest](https://jestjs.io/docs/expect#expectextendmatchers)
