Package detail

@anatine/zod-mock

anatine773.4kMIT3.14.0

Zod auto-mock object generator using Faker at @faker-js/faker

zod, mock, faker-js

readme

@anatine/zod-mock

Generates a mock data object using faker.js from a Zod schema.


Installation

@faker-js/faker is a peer dependency of @anatine/zod-mock and is used for mock data generation.

npm install zod @faker-js/faker @anatine/zod-mock

Usage

Take any Zod schema and create mock data

import { generateMock } from '@anatine/zod-mock';
const schema = z.object({
      uid: z.string().nonempty(),
      theme: z.enum([`light`, `dark`]),
      email: z.string().email().optional(),
      phoneNumber: z.string().min(10).optional(),
      avatar: z.string().url().optional(),
      jobTitle: z.string().optional(),
      otherUserEmails: z.array(z.string().email()),
      stringArrays: z.array(z.string()),
      stringLength: z.string().transform((val) => val.length),
      numberCount: z.number().transform((item) => `total value = ${item}`),
      age: z.number().min(18).max(120),
    });
const mockData = generateMock(schema);
// ...

This will generate mock data similar to:

{
  "uid": "3f46b40e-95ed-43d0-9165-0b8730de8d14",
  "theme": "light",
  "email": "Alexandre99@hotmail.com",
  "phoneNumber": "1-665-405-2226",
  "avatar": "https://cdn.fakercloud.com/avatars/olaolusoga_128.jpg",
  "jobTitle": "Lead Brand Facilitator",
  "otherUserEmails": [
    "Wyman58@example.net",
    "Ignacio_Nader@example.org",
    "Jorge_Bradtke@example.org",
    "Elena.Torphy33@example.org",
    "Kelli_Bartoletti@example.com"
  ],
  "stringArrays": [
    "quisquam",
    "corrupti",
    "atque",
    "sunt",
    "voluptatem"
  ],
  "stringLength": 4,
  "numberCount": "total value = 25430",
  "age": 110
}

Overriding string mocks

Sometimes there might be a reason to have a more specific mock for a string value.

You can supply an options field to generate specific mock data that will be triggered by the matching key.

const schema = z.object({
  locked: z.string(),
  email: z.string().email(),
  primaryColor: z.string(),
});
const mockData = generateMock(schema, {
  stringMap: {
    locked: () => `this return set to the locked value`,
    email: () => `not a email anymore`,
    primaryColor: () => faker.internet.color(),
  },
});

Adding a seed generator

For consistent testing, you can also add in a seed or seed array.

const schema = z.object({
  name: z.string(),
  age: z.number(),
});
const seed = 123;
const first = generateMock(schema, { seed });
const second = generateMock(schema, { seed });
expect(first).toEqual(second);

Adding a custom mock mapper

Once drilled down to deliver a string, number, boolean, or other primitive value a function with a matching name is searched for in faker.

You can add your own key/fn mapper in the options.


export function mockeryMapper(
  keyName: string,
  fakerInstance: Faker
): FakerFunction | undefined {
  const keyToFnMap: Record<string, FakerFunction> = {
    image: fakerInstance.image.url,
    imageurl: fakerInstance.image.url,
    number: fakerInstance.number.int,
    float: fakerInstance.number.float,
    hexadecimal: fakerInstance.number.hex,
    uuid: fakerInstance.string.uuid,
    boolean: fakerInstance.datatype.boolean,
    // Email more guaranteed to be random for testing
    email: () => fakerInstance.database.mongodbObjectId() + '@example.com'
  };
  return keyName && keyName.toLowerCase() in keyToFnMap
    ? keyToFnMap[keyName.toLowerCase() as never]
    : undefined;
}

const schema = z.object({
  locked: z.string(),
  email: z.string().email(),
  primaryColor: z.string(),
});

const result = generateMock(schema, { mockeryMapper });

Behind the Scenes

zod-mock tries to generate mock data from two sources.

  • Object key name ie({ firstName: z.string() })

    This will check the string name of the key against all the available faker function names. Upon a match, it uses that function to generate a mock value.

  • Zodtype ie(const something = z.string())

    In the case there is no key name (the schema doesn't contain an object) or there is no key name match, zod-mock will use the primitive type provided by zod.

    Some zod filter types (email, uuid, url, min, max, length) will also modify the results.

    If zod-mock does not yet support a Zod type used in your schema, you may provide a backup mock function to use for that particular type.

    const schema = z.object({
      anyVal: z.any()
    });
    const mockData = generateMock(schema, {
      backupMocks: {
        ZodAny: () => 'a value'
      }
    });

Missing Features

  • No pattern for passing options into faker, such as setting phone number formatting
  • Does not handle the following Zod types:
    • ZodAny
    • ZodDefault
    • ZodFunction
    • ZodIntersection
    • ZodMap
    • ZodPromise
    • ZodSet
    • ZodTuple
    • ZodUnion
    • ZodUnknown

Credits

  • express-zod-api

    A great lib that provided some insights on dealing with various zod types.


This library is part of a nx monorepo @anatine/zod-plugins.

changelog

Changelog

This file was generated using @jscutlery/semver.

3.14.0 (2025-04-04)

Features

  • zod-mock: add support for readonly fields (486eb3a)

Bug Fixes

  • zod-mock: update peer dependency range for @faker-js/faker to include ^9.x (6a89566)

3.13.5 (2025-01-20)

Bug Fixes

  • zod-mock: [#172] add support for mockeryMapper to be used for numbers, dates and booleans (cd50715)

3.13.4 (2024-03-19)

3.13.3 (2023-10-31)

3.13.2 (2023-07-31)

Bug Fixes

3.13.1 (2023-06-30)

3.13.0 (2023-06-30)

Bug Fixes

  • Logic for city key to map to name, not image (73cac73)

3.12.1 (2023-06-16)

3.12.0 (2023-05-23)

Features

3.11.0 (2023-04-23)

Features

  • zod-mock: pass zodRef and options to generator function which defined in backupMocks (a7a8acf)

3.10.0 (2023-03-22)

Features

  • extend native enum to support const assertion (c70336a)

3.9.0 (2023-02-27)

Features

  • zod-mock: mock strings with explicit length (c0f7670)

3.8.4 (2023-02-21)

Bug Fixes

3.8.3 (2023-01-17)

3.8.2 (2023-01-04)

3.8.1 (2023-01-01)

3.8.0 (2022-12-12)

Features

  • Optional faker class instance as an option (ec7b505)

3.7.0 (2022-12-12)

Features

Bug Fixes

  • array length in Zod Mock (2811101)

3.6.0 (2022-10-05)

Features

  • Support for @Param() in @anatine/zod-nestjs (ba00144)

3.5.11 (2022-09-12)

3.5.10 (2022-09-12)

3.5.9 (2022-09-05)

3.5.8 (2022-09-05)

3.5.7 (2022-08-17)

Bug Fixes

  • replace findName to fullName (8f04cbd)

3.5.6 (2022-07-28)

Bug Fixes

  • nativeEnum random pick function bias (a082988)

3.5.6 (2022-07-28)

Bug Fixes

  • nativeEnum random pick function bias (a082988)

3.5.5 (2022-07-26)

Bug Fixes

3.5.5 (2022-07-26)

Bug Fixes

3.5.5 (2022-07-26)

Bug Fixes

3.5.5 (2022-07-26)

Bug Fixes

3.5.5 (2022-07-26)

Bug Fixes

3.5.3 (2022-07-26)

3.4.0 (2022-07-24)

Bug Fixes

  • native enum error (1ad2dff)
  • parseNativeEnum arg type (5700a14)
  • record type and swap string min when greater than max (ae51c01)
  • type issue in zod-mock (b2cd0bd)

3.3.0 (2022-07-14)

0.0.2 (2022-07-14)

0.0.1 (2022-07-14)

Bug Fixes

  • Adding in new release githuib actions (29a2455)