zodios는 ZodError를 ZodiosError.cause에 담아 던진다1 — instanceof z.ZodError로는 안 잡힌다.
if (err instanceof ZodiosError && err.cause instanceof ZodError) {
console.log(fromZodError(err.cause).toString())
}
- isErrorFromAlias not finding errors when uri have undefined params · Issue #402 · ecyrbe/zodios
- https://www.jacobparis.com/content/type-safe-env
Footnotes
-
zodios
zod-validation.plugin.ts: 응답 검증 실패 시throw new ZodiosError(… config, response.data, parsed.error)— 네 번째 인자가cause다. ↩
process.env 를 스키마로 parse 하면 빠진 값은 시작할 때 ZodError 로 터지고1, 결과에는 선언한 키만 남는다2.
import z from 'zod'
const envSchema = z.object({
REACT_APP_FEATURE_VAC_ASK: z.string(),
REACT_APP_FEATURE_RECORDS: z.string(),
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
})
const windowSchema = z.object({
SOMETHING_COOL: z.string()
})
export const ENV = envSchema.parse(process.env)
export const WINDOW = windowSchema.parse(window)
- Using Zod to safely read env variables by sergiodxa
- GitHub - lostfictions/znv: Type-safe environment parsing and validation for Node.js with Zod schemas
- https://twitter.com/mattpocockuk/status/1615110808219918352?s=20
Footnotes
-
Basic usage | Zod: “When validation fails, the
.parse()method will throw aZodErrorinstance with granular information about the validation issues.” ↩ -
Defining schemas | Zod: “By default, unrecognized keys are stripped from the parsed result” ↩
vitest에서 사용자 지정 assertion을 추가하여 Zod 스키마와 Response 객체를 비교하기
// vitest 5.0 기준
import { expect } from 'vitest'
import type { MatcherResult } 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 MatcherResult
},
})
vitest.d.ts 에서 vitest 모듈의 Matchers 인터페이스를 확장한다. 비동기 매처라 반환 타입은 R 이 아니라 Promise<void>1.
import 'vitest'
import type { ZodTypeAny } from 'zod'
declare module 'vitest' {
interface Matchers<R, T> {
toMatchSchema: (schema: ZodTypeAny) => Promise<void>
}
}
todoResponse의 응답 데이터가 todoSchema에 정의된 Zod 스키마와 일치하는지 확인한다. 매처가 async라 테스트에서 await 한다1.
test('todo', async () => {
expect(todoResponse.ok).toBeTruthy()
await expect(todoResponse).toMatchSchema(todoSchema)
})
Footnotes
-
Extending Matchers | Guide | Vitest: “If a matcher implementation is asynchronous, declare its return type as
Promise<void>instead ofRand don’t forget toawaitit in the test” ↩ ↩2