npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@mikemajesty/zod-mock-schema

v1.0.13

Published

Generate mock data from Zod schemas

Readme

Zod Mock Schema

npm version License TypeScript Ready

A powerful and flexible class‑based utility for generating realistic mock data directly from Zod schemas — ideal for testing, prototyping, fixtures, and CI automation.

✨ Features

  • ✅ Class-based API for full control and extensibility
  • ✅ Faker.js integration for realistic fake data
  • ✅ Type‑safe overrides with full TypeScript support
  • ✅ Deep Zod schema integration with nested object support
  • ✅ Custom formats: CPF, CNPJ, RG, CEP, phone BR
  • ✅ Deterministic generation via Faker seeding
  • ✅ Batch creation with generateMany
  • ✅ Smart prefixing for unique, identifiable data
  • ✅ Index‑based generation for sequential data
  • ✅ Flexible field customization
  • ✅ Full Zod schema support (Union, Intersection, Record, Lazy, Pipe, etc.)

📦 Installation

# npm
npm install @mikemajesty/zod-mock-schema

# yarn
yarn add @mikemajesty/zod-mock-schema

# pnpm
pnpm add @mikemajesty/zod-mock-schema

Note: Zod and Faker are peer dependencies.


🚀 Quick Start

import { z } from 'zod';
import { ZodMockSchema } from '@mikemajesty/zod-mock-schema';

const userSchema = z.object({
  id: z.string().uuid(),
  name: z.string(),
  email: z.string().email(),
  age: z.number().int().min(18).max(99),
  isActive: z.boolean(),
  createdAt: z.date(),
});

const userMock = new ZodMockSchema(userSchema);

console.log(userMock.generate());

🔧 Basic Usage

1. Simple Mock

const productSchema = z.object({
  id: z.number(),
  title: z.string(),
  price: z.number().positive(),
  inStock: z.boolean(),
  tags: z.array(z.string()),
});

const productMock = new ZodMockSchema(productSchema);
productMock.generate();

2. Override Properties

userMock.generate({
  overrides: {
    name: 'Alice Johnson',
    age: 25,
    email: '[email protected]',
    createdAt: new Date('2023-01-01'),
  }
});

3. Generate Multiple Items

userMock.generateMany(3, {
  overrides: { department: 'Engineering' }
});

🎯 Smart Prefixing System

Random Prefix Selection

userMock.generateMany(5, {
  prefix: {
    options: ['USER', 'CLIENT', 'CUSTOMER', 'MEMBER'],
    for: 'username'
  }
});

Index-Based Prefixing

userMock.generateMany(3, {
  prefix: {
    options: { useIndex: true },
    for: 'email'
  }
});

🧠 Advanced Zod Schema Support

Complex Zod Types

const complexSchema = z.object({
  status: z.union([z.literal('active'), z.literal('inactive'), z.literal('pending')]),
  userWithRole: z.object({ name: z.string() }).and(z.object({ role: z.string() })),
  metadata: z.record(z.string()),
  optionalField: z.string().optional(),
  nullableField: z.string().nullable(),
  tags: z.array(z.string()).min(1).max(5),
  score: z.number().default(0),
  nested: z.lazy(() => complexSchema.optional()),
});

const complexMock = new ZodMockSchema(complexSchema);
complexMock.generate();

🇧🇷 Custom Brazilian Formats

const brazilSchema = z.object({
  cpf: z.string().meta({ format: 'cpf' }),
  cnpj: z.string().meta({ format: 'cnpj' }),
  rg: z.string().meta({ format: 'rg' }),
  phone: z.string().meta({ format: 'phoneBR' }),
  cep: z.string().meta({ format: 'cep' }),
});

new ZodMockSchema(brazilSchema).generate();

🛒 E-commerce Example

const orderSchema = z.object({
  id: z.string().uuid(),
  customerId: z.string().uuid(),
  items: z.array(z.object({
    productId: z.string().uuid(),
    quantity: z.number().int().positive(),
    price: z.number().positive(),
  })),
  total: z.number().positive(),
  status: z.enum(['pending', 'processing', 'shipped', 'delivered']),
  createdAt: z.date(),
  metadata: z.record(z.any()).optional(),
});

const orderMock = new ZodMockSchema(orderSchema);

orderMock.generateMany(5, {
  overrides: {
    status: 'processing',
    total: 1399.97,
  },
  prefix: {
    options: { useIndex: true },
    for: 'id'
  }
});

🏭 Factory Pattern

export class UserFactory {
  private mock = new ZodMockSchema(userSchema);

  create(overrides?: Partial<User>) {
    return this.mock.generate({ overrides });
  }

  createMany(count: number, options?: MockManyOptions<User>) {
    return this.mock.generateMany(count, options);
  }

  createAdmins(count: number) {
    return this.mock.generateMany(count, {
      overrides: { role: 'admin' },
      prefix: {
        options: ['ADM', 'ADMIN'],
        for: 'username'
      }
    });
  }
}

🧪 Testing Patterns

Deterministic Tests

faker.seed(123);
const user = userMock.generate();

Integration Testing

describe('User Service', () => {
  const userMock = new ZodMockSchema(userSchema);

  test('should create multiple unique users', () => {
    const users = userMock.generateMany(5, {
      prefix: {
        options: { useIndex: true },
        for: 'email'
      }
    });

    const emails = users.map(u => u.email);
    expect(new Set(emails).size).toBe(5);
  });
});

📘 API Reference

new ZodMockSchema(schema)

Creates a mock generator for the given Zod schema.

Methods

generate(options?: MockOptions<T>): T

Generates a single mock object.

generateMany(count: number, options?: MockManyOptions<T>): T[]

Generates multiple mock objects.


🔄 Supported Zod Types

✓ String · Number · Boolean · Date · Array
✓ Object · Union · Intersection · Enum
✓ Record · Optional · Nullable · Default
✓ Lazy · Literal · Any · Unknown
✓ Void · Null · Pipe


🧹 Best Practices

  • Reuse mock instances
  • Use overrides for business rules
  • Centralize factories
  • Use prefixing for unique data
  • Seed Faker for deterministic tests

📄 License

MIT © Mike Majesty