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.
@anatine/graphql-zod-validation
Fork for type support
This codebase is taken direction from GraphQL code generator
Used to generate validation schema from the following libraries.
NOTE
This module has additional support for generating type
objects from GraphQL
Useful when using the expected validation type (or one extended) to validate data before returning to your resolver.
Quick Start
Start by installing this plugin and write simple plugin config;
npm i @anatine/graphql-zod-validation
generates:
path/to/graphql.ts:
plugins:
- typescript
- '@anatine/graphql-zod-validation'
config:
strictScalars: true
schema: yup
You can check example directory if you want to see more complex config example or how is generated some files.
The Q&A for each schema is written in the README in the respective example directory.
Config API Reference
schema
type: ValidationSchema
default: 'yup'
Specify generete validation schema you want.
You can specify yup
or zod
or myzod
.
generates:
path/to/graphql.ts:
plugins:
- typescript
- '@anatine/graphql-zod-validation'
config:
schema: yup
importFrom
type: string
When provided, import types from the generated typescript types file path. if not given, omit import statement.
generates:
path/to/graphql.ts:
plugins:
- typescript
path/to/validation.ts:
plugins:
- '@anatine/graphql-zod-validation'
config:
importFrom: ./graphql
Then the generator generates code with import statement like below.
import { GeneratedInput } from './graphql'
typesPrefix
type: string
default: (empty)
Prefixes all import types from generated typescript type.
generates:
path/to/graphql.ts:
plugins:
- typescript
path/to/validation.ts:
plugins:
- '@anatine/graphql-zod-validation'
config:
typesPrefix: I
importFrom: ./graphql
Then the generator generates code with import statement like below.
import { IGeneratedInput } from './graphql'
typesSuffix
type: string
default: (empty)
Suffixes all import types from generated typescript type.
generates:
path/to/graphql.ts:
plugins:
- typescript
path/to/validation.ts:
plugins:
- '@anatine/graphql-zod-validation'
config:
typesSuffix: I
importFrom: ./graphql
Then the generator generates code with import statement like below.
import { GeneratedInputI } from './graphql'
enumsAsTypes
type: boolean
default: false
Generates enum as TypeScript type
instead of enum
.
notAllowEmptyString
type: boolean
default: false
Generates validation string schema as do not allow empty characters by default.
scalarSchemas
type: ScalarSchemas
Extends or overrides validation schema for the built-in scalars and custom GraphQL scalars.
useObjectTypes
type: boolean
default: false
When enabled, object types type
will also be converted via codegen.
yup schema
config:
schema: yup
scalarSchemas:
Date: yup.date()
Email: yup.string().email()
zod schema
config:
schema: zod
useObjectTypes: true
scalarSchemas:
Date: z.date()
Email: z.string().email()
directives
type: DirectiveConfig
Generates validation schema with more API based on directive schema. For example, yaml config and GraphQL schema is here.
input ExampleInput {
email: String! @required(msg: "Hello, World!") @constraint(minLength: 50, format: "email")
message: String! @constraint(startsWith: "Hello")
}
yup schema extended
generates:
path/to/graphql.ts:
plugins:
- typescript
- '@anatine/graphql-zod-validation'
config:
schema: yup
directives:
required:
msg: required
constraint:
minLength: min
startsWith: ["matches", "/^$1/"]
format:
email: email
Then generates yup validation schema like below.
export function ExampleInputSchema(): yup.SchemaOf<ExampleInput> {
return yup.object({
email: yup.string().defined().required("Hello, World!").min(50).email(),
message: yup.string().defined().matches(/^Hello/)
})
}
zod schema extended
generates:
path/to/graphql.ts:
plugins:
- typescript
- typescript-validation-schema
config:
schema: zod
directives:
constraint:
minLength: min
startsWith: ["regex", "/^$1/", "message"]
format:
email: email
Then generates zod validation schema like below.
export function ExampleInputSchema(): z.ZodSchema<ExampleInput> {
return z.object({
email: z.string().min(50).email(),
message: z.string().regex(/^Hello/, "message")
})
}
other schema
Please see example directory.