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

zod-to-mock-data

v1.0.0

Published

Generate realistic mock data from Zod schemas using Faker.js - smart field detection, type-safe, zero config

Downloads

104

Readme

zod-to-mock-data

Generate realistic, randomized mock data from Zod schemas

npm version TypeScript

A powerful TypeScript library that bridges Zod schemas with Faker.js to generate realistic mock data. Perfect for testing, prototyping, and Storybook components.

✨ Features

  • 🎯 Realistic by Default - Fields like email, firstName, and phone generate actual-looking data, not random gibberish
  • 🔄 Recursive Robustness - Handles deeply nested objects, arrays, optionals, and nullables without issues
  • 📦 Zero Configuration - Works out of the box with sensible defaults
  • 🔧 Fully Configurable - Customize array lengths, optional probability, and use seeds for reproducible data
  • 💪 Type-Safe - Perfect TypeScript inference—output type matches your Zod schema

📦 Installation

npm install zod-to-mock-data
# or
pnpm add zod-to-mock-data
# or
yarn add zod-to-mock-data

Note: zod is a peer dependency. Make sure you have it installed:

npm install zod

🚀 Quick Start

import { z } from 'zod';
import { generateMock } from 'zod-to-mock-data';

// Define your schema
const userSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  firstName: z.string(),
  lastName: z.string(),
  age: z.number().int().min(0).max(120),
  isActive: z.boolean(),
});

// Generate mock data
const mockUser = generateMock(userSchema);

console.log(mockUser);
// {
//   id: "550e8400-e29b-41d4-a716-446655440000",
//   email: "[email protected]",
//   firstName: "John",
//   lastName: "Smith",
//   age: 32,
//   isActive: true
// }

🧠 Smart Generation

The library intelligently maps Zod constraints and field names to appropriate Faker.js generators:

Priority 1: Zod String Checks

z.string().email()    // → faker.internet.email()
z.string().url()      // → faker.internet.url()
z.string().uuid()     // → faker.string.uuid()
z.string().datetime() // → faker.date.recent().toISOString()
z.string().ip()       // → faker.internet.ip()

Priority 2: Field Name Heuristics

When no Zod check is present, the field name guides generation:

const schema = z.object({
  firstName: z.string(),  // → faker.person.firstName()
  email: z.string(),      // → faker.internet.email()
  phone: z.string(),      // → faker.phone.number()
  avatar: z.string(),     // → faker.image.avatar()
  city: z.string(),       // → faker.location.city()
  company: z.string(),    // → faker.company.name()
  description: z.string() // → faker.lorem.paragraph()
});

Supported Field Name Patterns

| Category | Field Names | |----------|------------| | Person | firstName, lastName, fullName, name, middleName, prefix, suffix, gender, jobTitle | | Contact | email, phone, mobile, telephone | | Internet | username, password, url, website, avatar, image, ip, userAgent | | Address | street, address, city, state, country, zip, postalCode, latitude, longitude, timezone | | Company | company, organization, department | | Content | title, description, content, body, bio, comment, slug | | Identifiers | id, uuid, guid, sku | | Finance | currency, creditCard, iban, bic | | Dates | date, createdAt, updatedAt, birthDate | | Files | filename, mimeType, extension, path |

⚙️ Configuration Options

interface MockOptions {
  seed?: number;              // For reproducible generation
  arrayMinLength?: number;    // Min items in arrays (default: 1)
  arrayMaxLength?: number;    // Max items in arrays (default: 5)
  optionalProbability?: number; // Chance of generating optional fields (default: 0.8)
  nullableProbability?: number; // Chance of value vs null (default: 0.8)
}

Reproducible Data with Seeds

const schema = z.object({
  name: z.string(),
  age: z.number(),
});

// Same seed = same output every time
const data1 = generateMock(schema, { seed: 12345 });
const data2 = generateMock(schema, { seed: 12345 });

console.log(data1); // { name: "John", age: 42 }
console.log(data2); // { name: "John", age: 42 } - identical!

Controlling Arrays

const schema = z.object({
  tags: z.array(z.string()),
});

const data = generateMock(schema, {
  arrayMinLength: 3,
  arrayMaxLength: 10,
});

// data.tags will have 3-10 items

Optional Fields

const schema = z.object({
  required: z.string(),
  maybeValue: z.string().optional(),
});

// Always generate optional fields
generateMock(schema, { optionalProbability: 1 });

// Never generate optional fields
generateMock(schema, { optionalProbability: 0 });

📋 Supported Zod Types

| Type | Support | Notes | |------|---------|-------| | z.string() | ✅ | Smart generation with checks & key heuristics | | z.number() | ✅ | Respects min/max/int/positive/multipleOf | | z.boolean() | ✅ | Random true/false | | z.date() | ✅ | Recent dates | | z.bigint() | ✅ | Random BigInt values | | z.literal() | ✅ | Returns exact value | | z.enum() | ✅ | Random pick from options | | z.nativeEnum() | ✅ | Supports TS enums | | z.object() | ✅ | Recursive with key context | | z.array() | ✅ | Configurable length | | z.tuple() | ✅ | Preserves order and types | | z.record() | ✅ | Random string keys | | z.map() | ✅ | Map with generated entries | | z.set() | ✅ | Set with unique values | | z.union() | ✅ | Random option selection | | z.discriminatedUnion() | ✅ | Handles discriminators | | z.intersection() | ✅ | Merges objects | | z.optional() | ✅ | Configurable probability | | z.nullable() | ✅ | Configurable probability | | z.default() | ✅ | Generates inner type | | z.catch() | ✅ | Generates inner type | | z.lazy() | ✅ | Evaluates and generates | | z.readonly() | ✅ | Generates inner type | | z.null() | ✅ | Returns null | | z.undefined() | ✅ | Returns undefined | | z.any() / z.unknown() | ✅ | Random primitive | | z.never() | ❌ | Throws error | | z.transform() | ⚠️ | Generates input schema | | z.preprocess() | ⚠️ | Generates inner schema |

🎯 Real-World Example

import { z } from 'zod';
import { generateMock } from 'zod-to-mock-data';

// E-commerce order schema
const orderSchema = z.object({
  orderId: z.string().uuid(),
  customer: z.object({
    id: z.string().uuid(),
    email: z.string().email(),
    firstName: z.string(),
    lastName: z.string(),
    phone: z.string(),
  }),
  items: z.array(z.object({
    productId: z.string().uuid(),
    name: z.string(),
    quantity: z.number().int().min(1).max(10),
    price: z.number().min(0),
  })),
  shippingAddress: z.object({
    street: z.string(),
    city: z.string(),
    state: z.string(),
    zip: z.string(),
    country: z.string(),
  }),
  status: z.enum(['pending', 'processing', 'shipped', 'delivered']),
  notes: z.string().optional(),
  createdAt: z.string().datetime(),
});

// Generate 5 mock orders for testing
const mockOrders = Array.from({ length: 5 }, () => 
  generateMock(orderSchema)
);

🧪 Use Cases

  • Unit Testing - Generate test fixtures that match your schemas
  • Storybook - Populate components with realistic data
  • API Mocking - Create mock API responses during development
  • Prototyping - Quickly visualize UIs with realistic content
  • Database Seeding - Generate sample data for development databases

📄 License

MIT © 2024