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
Maintainers
Readme
zod-to-mock-data
Generate realistic, randomized mock data from Zod schemas
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, andphonegenerate 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-dataNote:
zodis 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 itemsOptional 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
