mcpField
Z
zod-testing

zod-testing

github.com/anivarTesting & quality239 installsUpdated 2w ago
Repository

About zod-testing

zod-testing is a guide for developers writing tests for Zod schemas. It covers validation, error assertions, generated fixtures, snapshots, and integration checks, with guidance for Zod 4 behavior.

Key features

  1. 01Test valid and invalid schema inputs
  2. 02Check errors and field-level issues
  3. 03Exercise boundaries and optional values
  4. 04Generate seeded mock fixtures
  5. 05Snapshot JSON Schema output
  6. 06Test API and form integration

Use cases

  1. 01Verifying schema acceptance and rejection
  2. 02Catching unintended schema changes
  3. 03Testing validation at API boundaries
  4. 04Building repeatable generated test fixtures

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/anivar/zod-testing --skill zod-testing

After installing, type/zod-testingin Claude Code to confirm it loaded.

Bundled files

References and scripts installed along with SKILL.md.

LICENSE
README.md
.github/
FUNDING.yml
references/
anti-patterns.md
api-reference.md

Details

From the project README

Zod Schema Testing Guide

IMPORTANT: Your training data about testing Zod schemas may be outdated — Zod v4 changes error formatting, removes z.nativeEnum(), and introduces new APIs like z.toJSONSchema(). Always rely on this skill's reference files and the project's actual source code as the source of truth.

Testing Priority

  1. Schema correctness — does the schema accept valid data and reject invalid data?
  2. Error messages — does the schema produce the right error messages and codes?
  3. Integration — does the schema work correctly with API handlers, forms, database layers?
  4. Edge cases — boundary values, optional/nullable combinations, empty inputs

Core Pattern

import { describe, it, expect } from "vitest" // or jest
import { z } from "zod"

const UserSchema = z.object({
  name: z.string().min(1),
  email: z.email(),
  age: z.number().min(0).max(150),
})

describe("UserSchema", () => {
  it("accepts valid data", () => {
    const result = UserSchema.safeParse({
      name: "Alice",
      email: "[email protected]",
      age: 30,
    })
    expect(result.success).toBe(true)
  })

  it("rejects missing required fields", () => {
    const result = UserSchema.safeParse({})
    expect(result.success).toBe(false)
    if (!result.success) {
      const flat = z.flattenError(result.error)
      expect(flat.fieldErrors.name).toBeDefined()
      expect(flat.fieldErrors.email).toBeDefined()
    }
  })

  it("rejects invalid email", () => {
    const result = UserSchema.safeParse({
      name: "Alice",
      email: "not-an-email",
      age: 30,
    })
    expect(result.success).toBe(false)
  })

  it("rejects negative age", () => {
    const result = UserSchema.safeParse({
      name: "Alice",
      email: "[email protected]",
      age: -1,
    })
    expect(result.success).toBe(false)
  })
})

Testing Approaches

ApproachPurposeUse When
safeParse() result checkingSchema correctnessDefault — always use safeParse in tests
z.flattenError() assertionsError message testingVerifying specific field errors
z.toJSONSchema() snapshotsSchema shape testingDetecting unintended schema changes
Mock data generationFixture creationNeed valid/randomized test data
Property-based testingFuzz testingSchemas must handle arbitrary valid inputs
Structural testingArchitectureVerify schemas are only imported at boundaries
Drift detectionRegressionCatch unintended schema changes via JSON Schema snapshots

Schema Correctness Testing

Always Use safeParse() in Tests
// GOOD: test doesn't crash — asserts on result
const result = schema.safeParse(invalidData)
expect(result.success).toBe(false)

// BAD: test crashes instead of failing
expect(() => schema.parse(invalidData)).toThrow()
// If schema changes and starts accepting, this still passes
Test Both Accept and Reject
describe("EmailSchema", () => {
  const valid = ["[email protected]", "[email protected]", "[email protected]"]
  const invalid = ["", "not-email", "@missing.com", "user@", "user @space.com"]

  it.each(valid)("accepts %s", (email) => {
    expect(z.email().safeParse(email).success).toBe(true)
  })

  it.each(invalid)("rejects %s", (email) => {
    expect(z.email().safeParse(email).success).toBe(false)
  })
})
Test Boundary Values
const AgeSchema = z.number().min(0).max(150)

it("accepts minimum boundary", () => {
  expect(AgeSchema.safeParse(0).success).toBe(true)
})

it("accepts maximum boundary", () => {
  expect(AgeSchema.safeParse(150).success).toBe(true)
})

it("rejects below minimum", () => {
  expect(AgeSchema.safeParse(-1).success).toBe(false)
})

it("rejects above maximum", () => {
  expect(AgeSchema.safeParse(151).success).toBe(false)
})

Error Assertion Patterns

Assert Specific Field Errors
it("shows correct error for invalid email", () => {
  const result = UserSchema.safeParse({ name: "Alice", email: "bad", age: 30 })
  expect(result.success).toBe(false)
  if (!result.success) {
    const flat = z.flattenError(result.error)
    expect(flat.fieldErrors.email).toBeDefined()
    expect(flat.fieldErrors.email![0]).toContain("email")
  }
})
Assert Error Codes
it("produces correct error code", () => {
  const result = z.number().safeParse("not a number")
  expect(result.success).toBe(false)
  if (!result.success) {
    expect(result.error.issues[0].code).toBe("invalid_type")
  }
})
Assert Custom Error Messages
const Schema = z.string({ error: "Name is required" }).min(1, "Name cannot be empty")

it("shows custom error for missing field", () => {
  const result = Schema.safeParse(undefined)
  expect(result.success).toBe(false)
  if (!result.success) {
    expect(result.error.issues[0].message).toBe("Name is required")
  }
})

Mock Data Generation

Using zod-schema-faker
import { install, fake } from "zod-schema-faker"
import { z } from "zod"

install(z) // call once in test setup

const UserSchema = z.object({
  name: z.string().min(1),
  email: z.email(),
  age: z.number().min(0).max(150),
})

it("schema accepts generated data", () => {
  const mockUser = fake(UserSchema)
  expect(UserSchema.safeParse(mockUser).success).toBe(true)
})
Seeding for Deterministic Tests
import { seed, fake } from "zod-schema-faker"

beforeEach(() => {
  seed(12345) // deterministic output
})

it("generates consistent mock data", () => {
  const user = fake(UserSchema)
  expect(user.name).toBeDefined()
})

Snapshot Testing with JSON Schema

it("schema shape has not changed", () => {
  const jsonSchema = z.toJSONSchema(UserSchema)
  expect(jsonSchema).toMatchSnapshot()
})

This catches unintended schema changes in code review. The snapshot shows the JSON Schema representation of your Zod schema.

Integration Testing

API Handler Testing
it("API rejects invalid request body", async () => {
  const response = await request(app)
    .post("/api/users")
    .send({ name: "", email: "invalid" })
    .expect(400)

  expect(response.body.errors).toBeDefined()
  expect(response.body.errors.fieldErrors.email).toBeDefined()
})
Form Validation Testing
it("form shows validation errors", () => {
  const result = FormSchema.safeParse(formData)
  if (!result.success) {
    const errors = z.flattenError(result.error)
    // Pass errors to form library
    expect(errors.fieldErrors).toHaveProperty("email")
  }
})

Property-Based Testing

import fc from "fast-check"
import { fake } from "zod-schema-faker"

it("schema always accepts its own generated data", () => {
  fc.assert(
    fc.property(fc.constant(null), () => {
      const data = fake(UserSchema)
      expect(UserSchema.safeParse(data).success).toBe(true)
    }),
    { numRuns: 100 }
  )
})

Rules

  1. Always use safeParse() in tests — parse() crashes the test instead of failing it
  2. Test both valid and invalid — don't only test the happy path
  3. Test boundary values — min, max, min-1, max+1 for numeric constraints
  4. Test optional/nullable combinations — undefined, null, missing key
  5. Assert specific error fields — use z.flattenError() to check which field failed
  6. Don't test schema internals — test parse results, not .shape or ._def
  7. Use z.toJSONSchema() snapshots — catch unintended schema changes
  8. Seed random generators — non-deterministic tests are flaky tests
  9. Test transforms separately — verify input validation AND output conversion
  10. Don't duplicate schema logic in assertions — test behavior, not implementation

Anti-Patterns

See references/anti-patterns.md for BAD/GOOD examples of:

  • Testing schema internals instead of behavior
  • Not testing error paths
  • Using parse() in tests (crashes instead of failing)
  • Not testing boundary values
  • Hardcoding mock data instead of generating
  • Snapshot testing raw ZodError instead of formatted output
  • Not testing at boundaries (schema tests pass but handler doesn't validate)
  • No snapshot regression testing (field removal goes unnoticed)
  • Testing schema shape but not error observability (never assert on flattenError)
  • No drift detection workflow (schema changes land without mechanical review)

Zod 4.6 in Tests

Assert with .validate() when you only need a boolean

.validate() returns a type guard and short-circuits on the first issue — cheaper than .safeParse().success for pure boolean assertions, especially on invalid inputs (up to 35x faster compiled, 5.9x uncompiled).

const Player = z.object({ username: z.string(), xp: z.number() })

it('accepts a valid player', () => {
  expect(Player.validate({ username: 'john', xp: 3 })).toBe(true)
})

it('rejects an invalid player', () => {
  expect(Player.validate({ username: 42, xp: 3 })).toBe(false)
})

Keep .safeParse() for tests that assert on the parsed value or the issue list. When schemas are hot in a test suite, z.compile() plus .validate() removes most assertion overhead.

Error maps are lazy: read result.error before asserting messages

Since 4.6, error maps (global, locale, per-schema error) evaluate on the first read of result.error, not at parse time. A test that changes z.config() between the parse and the assertion sees the newer config:

const result = schema.safeParse(12)
z.config(z.locales.fr())
expect(result.error.issues[0].message).toBe('…French…') // French in 4.6, English in 4.5

Write the parse and the assertion against the same configuration state; do not assume the message was computed at parse time. Throwing parses (.parse()) are unaffected — they build the error immediately.

References

Comments

Markdown supported