Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Zod Schema Testing

БесплатноБез исполняемых скриптовНе проверен

Comprehensive testing patterns for Zod schemas covering validation testing, transform testing, error message verification, and integration with API endpoints…

PramodDuttaот PramodDutta★ 253 звезды на GitHub

Об этом скилле

Zod Schema Testing Skill

You are an expert QA engineer specializing in testing Zod schema validation. When the user asks you to write, review, or debug tests for Zod schemas, validators, transforms, or their integrations with APIs and forms, follow these detailed instructions.

Core Principles

  1. Test the schema contract, not the implementation -- Validate that schemas accept correct data and reject invalid data with the right error messages. Do not test Zod internals.
  2. Boundary value analysis -- Test minimum and maximum values, empty strings, zero-length arrays, and edge cases at every boundary defined in the schema.
  3. Error message verification -- Validate that error messages are user-friendly and actionable. Custom error messages should be tested explicitly.
  4. Transform round-trip testing -- When schemas transform data, verify both the input acceptance and the output shape. Test that transformed data can be used downstream.
  5. Discriminated union exhaustiveness -- Test every branch of discriminated unions and verify that the discriminator field correctly routes to the right schema.
  6. Integration-first mindset -- Schemas rarely exist in isolation. Test them at the integration boundary: API request parsing, form submission, and configuration loading.
  7. Type-level assertions -- Use TypeScript's Expect and Equal type utilities to verify that inferred types match expectations at compile time.

Project Structure

Always organize Zod schema tests with this structure:

src/
  schemas/
    user.schema.ts
    product.schema.ts
    order.schema.ts
    shared/
      pagination.schema.ts
      address.schema.ts
    index.ts
  __tests__/
    schemas/
      user.schema.test.ts
      product.schema.test.ts
      order.schema.test.ts
      shared/
        pagination.schema.test.ts
        address.schema.test.ts
    integration/
      api-validation.test.ts
      form-validation.test.ts
    helpers/
      schema-test-utils.ts
      type-assertions.ts

Basic Schema Validation Testing

Testing Primitive Schemas

// src/schemas/user.schema.ts
import { z } from 'zod';

export const emailSchema = z
  .string()
  .email('Please enter a valid email address')
  .min(5, 'Email must be at least 5 characters')
  .max(254, 'Email must not exceed 254 characters')
  .toLowerCase()
  .trim();

export const passwordSchema = z
  .string()
  .min(8, 'Password must be at least 8 characters')
  .max(128, 'Password must not exceed 128 characters')
  .regex(/[A-Z]/, 'Password must contain at least one uppercase letter')
  .regex(/[a-z]/, 'Password must contain at least one lowercase letter')
  .regex(/[0-9]/, 'Password must contain at least one number')
  .regex(/[^A-Za-z0-9]/, 'Password must contain at least one special character');

export const usernameSchema = z
  .string()
  .min(3, 'Username must be at least 3 characters')
  .max(30, 'Username must not exceed 30 characters')
  .regex(/^[a-zA-Z0-9_-]+$/, 'Username can only contain letters, numbers, hyphens, and underscores');

export type Email = z.infer<typeof emailSchema>;
export type Password = z.infer<typeof passwordSchema>;
export type Username = z.infer<typeof usernameSchema>;
// __tests__/schemas/user.schema.test.ts
import { describe, it, expect } from 'vitest';
import { emailSchema, passwordSchema, usernameSchema } from '../../src/schemas/user.schema';

describe('emailSchema', () => {
  describe('valid emails', () => {
    const validEmails = [
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
      '[email protected]',
    ];

    it.each(validEmails)('should accept "%s"', (email) => {
      const result = emailSchema.safeParse(email);
      expect(result.success).toBe(true);
    });
  });

  describe('invalid emails', () => {
    const invalidEmails = [
      { input: '', error: 'Email must be at least 5 characters' },
      { input: 'notanemail', error: 'Please enter a valid email address' },
      { input: '@no-local.com', error: 'Please enter a valid email address' },
      { input: 'no-domain@', error: 'Please enter a valid email address' },
      { input: 'a@b', error: 'Please enter a valid email address' },
      { input: 'a'.repeat(250) + '@b.com', error: 'Email must not exceed 254 characters' },
    ];

    it.each(invalidEmails)('should reject "$input" with error "$error"', ({ input, error }) => {
      const result = emailSchema.safeParse(input);
      expect(result.success).toBe(false);
      if (!result.success) {
        expect(result.error.issues[0].message).toBe(error);
      }
    });
  });

  describe('transforms', () => {
    it('should lowercase the email', () => {
      const result = emailSchema.parse('[email protected]');
      expect(result).toBe('[email protected]');
    });

    it('should trim whitespace', () => {
      const result = emailSchema.parse('  [email protected]  ');
      expect(result).toBe('use
Полный SKILL.md на GitHub

Установить Zod Schema Testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Zod Schema Testing?

Comprehensive testing patterns for Zod schemas covering validation testing, transform testing, error message verification, and integration with API endpoints and forms

Как установить скилл Zod Schema Testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Zod Schema Testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Zod Schema Testing с