What is @anatine/zod-mock?
@anatine/zod-mock is an npm package that provides utilities for generating mock data based on Zod schemas. It is particularly useful for testing and development purposes where you need to create consistent and realistic mock data that adheres to your Zod schema definitions.
What are @anatine/zod-mock's main functionalities?
Generate Mock Data
This feature allows you to generate mock data based on a Zod schema. In this example, a user schema is defined with an id, name, and age. The `mock` function generates a mock user object that adheres to this schema.
const { z } = require('zod');
const { mock } = require('@anatine/zod-mock');
const userSchema = z.object({
id: z.string().uuid(),
name: z.string(),
age: z.number().int().min(18).max(99)
});
const mockUser = mock(userSchema);
console.log(mockUser);
Custom Mock Generators
This feature allows you to set custom mock generators for specific Zod types. In this example, a custom UUID generator is set, and the `mock` function uses this custom generator when creating the mock user object.
const { z } = require('zod');
const { mock, setMock } = require('@anatine/zod-mock');
const userSchema = z.object({
id: z.string().uuid(),
name: z.string(),
age: z.number().int().min(18).max(99)
});
setMock(z.string().uuid(), () => 'custom-uuid');
const mockUser = mock(userSchema);
console.log(mockUser);
Nested Schemas
This feature supports generating mock data for schemas with nested objects. In this example, a user schema includes an address schema, and the `mock` function generates a mock user object with a nested address object.
const { z } = require('zod');
const { mock } = require('@anatine/zod-mock');
const addressSchema = z.object({
street: z.string(),
city: z.string(),
zipCode: z.string().length(5)
});
const userSchema = z.object({
id: z.string().uuid(),
name: z.string(),
age: z.number().int().min(18).max(99),
address: addressSchema
});
const mockUser = mock(userSchema);
console.log(mockUser);
Other packages similar to @anatine/zod-mock
faker
Faker is a popular library for generating fake data. It provides a wide range of data types and is highly customizable. Unlike @anatine/zod-mock, Faker does not integrate directly with Zod schemas but offers more extensive data generation capabilities.
chance
Chance is another library for generating random data. It is lightweight and easy to use, offering a variety of data types. Similar to Faker, Chance does not integrate with Zod schemas but is useful for generating random data for testing purposes.
test-data-bot
Test Data Bot is a library for generating test data using a builder pattern. It allows for the creation of complex data structures and is highly customizable. While it does not integrate with Zod schemas, it provides a flexible way to generate test data.