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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@mikemajesty/zod-mock-schema

v1.0.18

Published

Generate mock data from Zod schemas

Readme

Zod Mock Schema

npm version License TypeScript Ready

Simple, type-safe mock data generator for Zod schemas with built-in Brazilian format support 🇧🇷

A developer-friendly, class-based utility for generating realistic test data from Zod schemas. Perfect for testing, prototyping, and fixtures — with zero configuration and maximum type safety.

✨ Why Choose This Library?

🎯 Simplicity First

  • Clean class-based API — instantiate once, generate many times
  • Zero configuration — works out of the box with any Zod schema
  • Type-safe overrides — full TypeScript intellisense and validation
  • Intuitive seedingmock.seed(123) for deterministic tests

🇧🇷 Brazilian Format Support (Unique Feature)

  • CPF, CNPJ, RG — built-in Brazilian document formats
  • CEP — postal code generation
  • Phone BR — Brazilian phone numbers
  • Zero dependencies — no extra libraries needed

Developer Experience

  • Faker.js integration — realistic, locale-aware fake data
  • Custom Faker injection — use different locales per test
  • Batch generationgenerateMany() for multiple mocks
  • Full Zod v4 support — Union, Intersection, Record, Lazy, Pipe, and more

📦 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(),
});x

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'
  }
});

🇧🇷 Brazilian Formats (Unique Feature)

Generate valid Brazilian documents and identifiers with zero configuration:

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

const userSchema = z.object({
  cpf: z.string().meta({ format: 'cpf' }),      // 11-digit CPF
  cnpj: z.string().meta({ format: 'cnpj' }),   // 14-digit CNPJ
  rg: z.string().meta({ format: 'rg' }),       // Brazilian ID
  phone: z.string().meta({ format: 'phoneBR' }), // BR phone number
  cep: z.string().meta({ format: 'cep' }),     // Postal code
});

const mock = new ZodMockSchema(userSchema);
const user = mock.generate();
// {
//   cpf: "52998224725",
//   cnpj: "60676960000106",
//   rg: "238192611",
//   phone: "11987654321",
//   cep: "01001000"
// }

// TypeScript support for format validation
const format: BrazilianFormat = 'cpf'; // Type-safe!

### Why This Matters

Brazilian formats require specific validation rules that generic mock generators don't understand. This library provides:

- ✅ **Pre-validated samples** — all generated values pass real validation
- ✅ **No external APIs** — works offline, no rate limits
- ✅ **Deterministic with seeds** — same seed = same CPF/CNPJ
- ✅ **Works in arrays and nested objects** — generate multiple documents easily

```ts
// Generate multiple users with valid Brazilian docs
const users = mock.generateMany(10);
users.forEach(u => console.log(u.cpf)); // All valid CPFs

🧠 Full Zod Schema Support

Supports all Zod types including advanced patterns:

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();

🛒 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,
  }
});

🏭 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' }
    });
  }
}

🧪 Testing Patterns

Deterministic Tests

const userMock = new ZodMockSchema(userSchema);
userMock.seed(123);
const user = userMock.generate();

Custom Faker Instance

Inject a custom Faker instance with different locales or configurations:

import { Faker, pt_BR } from '@faker-js/faker';

const customFaker = new Faker({ locale: pt_BR });
const user = userMock.generate({ faker: customFaker });

Parallel Tests with Isolated Faker Instances

test('parallel test 1', () => {
  const faker1 = new Faker({ locale: en });
  faker1.seed(100);
  const user = userMock.generate({ faker: faker1 });
});

test('parallel test 2', () => {
  const faker2 = new Faker({ locale: es });
  faker2.seed(200);
  const user = userMock.generate({ faker: faker2 });
});

Integration Testing

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

  test('should create multiple unique users', () => {
    const users = userMock.generateMany(5);

    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.

Exported Types

MockOptions<T>

Configuration options for generating a single mock object.

  • overrides?: Partial<T> — Override specific properties
  • faker?: Faker — Custom Faker instance for localization

MockManyOptions<T>

Extends MockOptions<T> for batch generation.

BrazilianFormat

Type-safe union of Brazilian format identifiers:

type BrazilianFormat = 'cpf' | 'cnpj' | 'rg' | 'phoneBR' | 'cep';

🔄 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

Keep It Simple

// ✅ Good: Reuse instances
const userMock = new ZodMockSchema(userSchema);
const user1 = userMock.generate();
const user2 = userMock.generate();

// ❌ Avoid: Creating new instances every time
const user1 = new ZodMockSchema(userSchema).generate();
const user2 = new ZodMockSchema(userSchema).generate();

Use Overrides for Business Logic

// ✅ Good: Override specific fields
userMock.generate({ overrides: { role: 'admin', status: 'active' } });

// ❌ Avoid: Manually modifying generated data
const user = userMock.generate();
user.role = 'admin'; // Bypasses Zod validation

Centralize Test Factories

// ✅ Good: Single source of truth
export const UserFactory = new ZodMockSchema(userSchema);

// In tests:
import { UserFactory } from './factories';
const admin = UserFactory.generate({ overrides: { role: 'admin' } });

Use Seeds for Deterministic Tests

// ✅ Good: Reproducible tests
test('user creation', () => {
  userMock.seed(12345);
  const user = userMock.generate();
  expect(user.name).toBe('Alice'); // Always the same with same seed
});

📄 License

MIT © Mike Majesty