### Install Zocker Source: https://github.com/lorissigrist/zocker/blob/main/README.md Install Zocker as a development dependency using npm. ```bash npm install --save-dev zocker ``` -------------------------------- ### Reuse Zocker Configurations Source: https://github.com/lorissigrist/zocker/blob/main/README.md Zocker's API is immutable, allowing reuse of configurations for generating variations of data. Create a base zocker setup and apply additional customizations for specific tests. ```typescript const zock = zocker(my_schema).supply(...)...setSeed(0); //Do a bunch of customization test("test 1" , ()=>{ const data = zock .supply(my_sub_schema, 0); //Extra-customization - Does not affect `zock` .generate() ... }) test("test 2", ()=> { const data = zock .supply(my_sub_schema, 1); //Extra-customization - Does not affect `zock` .generate() ... }) ``` -------------------------------- ### Customize Zocker Generation Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Customize built-in generators by passing options to their corresponding methods on zocker. For example, set the min/max for sets or the chance of extreme values for numbers. ```typescript const data = zocker(my_schema) .set({ min: 2, max: 20 }) //How many items should be in a set .number({ extreme_value_chance: 0.3 }) //The probability that the most extreme value allowed will be generated ... .generate() ``` -------------------------------- ### Generating Cyclic Types with z.lazy Source: https://github.com/lorissigrist/zocker/blob/main/README.md Zocker supports z.lazy for generating cyclic data structures. This example demonstrates creating a schema for nested JSON-like data, including literals, arrays, and records. ```typescript const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); const jsonSchema = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) ); const data = zocker(jsonSchema).setDepthLimit(5).generate(); //defaults to 5 ``` -------------------------------- ### Control Collection Sizes with .set(), .map(), .record() Source: https://context7.com/lorissigrist/zocker/llms.txt Configure the minimum and maximum number of elements for Sets, Maps, and Records generated by Zocker. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ tags: z.set(z.string()), metadata: z.map(z.string(), z.number()), attributes: z.record(z.string(), z.boolean()) }); const data = zocker(schema) .set({ min: 3, max: 5 }) .map({ min: 2, max: 4 }) .record({ min: 1, max: 3 }) .generate(); // Output: // { // tags: Set(4) { "alpha", "beta", "gamma", "delta" }, // metadata: Map(3) { "key1" => 42, "key2" => 17, "key3" => 89 }, // attributes: { "attr1": true, "attr2": false } // } ``` -------------------------------- ### Generate Mock Data with Zocker Source: https://github.com/lorissigrist/zocker/blob/main/README.md Import Zod and Zocker, define a Zod schema, and use zocker(schema).generate() to create mock data. Supports recursive schemas. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const person_schema = z.object({ name: z.string(), age: z.number(), emails: z.array(z.email()), children: z.array(z.lazy(() => person_schema)) }); const mockData = zocker(person_schema).generate(); /* mockData = { name: "John Doe", age: 42, emails: ["john.doe@gmail.com"], children: [ { name: "Jane Doe", age: 12, emails: [...] children: [...] }, ... ] } */ ``` ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const person_schema = z.object({ name: z.string(), age: z.number(), emails: z.array(z.string().email()), children: z.array(z.lazy(() => person_schema)) }); const mockData = zocker(person_schema).generate(); /* { name: "John Doe", age: 42, emails: ["john.doe@gmail.com"], children: [ { name: "Jane Doe", age: 12, emails: [...] children: [...] }, ... ] } */ ``` -------------------------------- ### Handling Cyclic Types Source: https://github.com/lorissigrist/zocker/blob/main/README.md Demonstrates how to generate cyclic data structures using `z.lazy`. ```APIDOC ## Cyclic Types Zocker supports `z.lazy`. You can use it to generate cyclic data.like normal ### Method ```typescript const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); const jsonSchema = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) ); const data = zocker(jsonSchema).setDepthLimit(5).generate(); //defaults to 5 ``` ``` -------------------------------- ### Options: .record() for ZodRecord Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodRecord` generator, such as `min` and `max` sizes. ```APIDOC ## .record Options for the built-in `z.ZodRecord` generator. ### Request Body ```json { "max": 10, "min": 0 } ``` ``` -------------------------------- ### Control .any() and .unknown() Generation Strategies Source: https://context7.com/lorissigrist/zocker/llms.txt Specify how `z.any()` and `z.unknown()` schemas should be generated using different strategies like 'true-any', 'json-compatible', or 'fast'. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ data: z.any(), payload: z.unknown() }); // "true-any": Generate any JavaScript value (default) const trueAny = zocker(schema) .any({ strategy: "true-any" }) .unknown({ strategy: "true-any" }) .generate(); // "json-compatible": Generate only JSON-serializable values const jsonSafe = zocker(schema) .any({ strategy: "json-compatible" }) .unknown({ strategy: "json-compatible" }) .generate(); // "fast": Generate simple primitive values quickly const fast = zocker(schema) .any({ strategy: "fast" }) .unknown({ strategy: "fast" }) .generate(); ``` -------------------------------- ### Regular Expressions Support Source: https://github.com/lorissigrist/zocker/blob/main/README.md Utilizes `z.string().regex()` for generating strings that match a given regular expression, leveraging the `randexp` library. ```APIDOC ## Regular Expressions Zocker supports `z.string().regex()` out of the box, thanks to the amazing [randexp](https://npmjs.com/package/randexp) library. It doesn't play very well with other string validators though (e.g `min`, `length` and other formats), so try to encode as much as possible in the regex itself. If you need to, you can always supply your own generator. ### Method ```typescript const regex_schema = z.string().regex(/^[a-z0-9]{5,10}$/); const data = zocker(regex_schema); // 1b3d5 ``` ``` -------------------------------- ### Options: .set() for ZodSet Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodSet` generator, such as `min` and `max` sizes. ```APIDOC ## .set Options for the built-in `z.ZodSet` generator. ### Request Body ```json { "max": 10, "min": 0 } ``` ``` -------------------------------- ### Generating Data with .generate() Source: https://github.com/lorissigrist/zocker/blob/main/README.md The `.generate()` method executes the data generation process based on the provided schema and configuration. It returns the generated data that conforms to the schema. ```typescript const data = zocker(schema).generate(); ``` -------------------------------- ### Options: .map() for ZodMap Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodMap` generator, such as `min` and `max` sizes. ```APIDOC ## .map Options for the built-in `z.ZodMap` generator. ### Request Body ```json { "max": 10, "min": 0 } ``` ``` -------------------------------- ### Configure Array Generation with .array() Source: https://context7.com/lorissigrist/zocker/llms.txt Customize array generation using `.array()` to set global minimum and maximum lengths. Schema-defined constraints like `.min()`, `.max()`, and `.length()` take precedence over these global settings. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ tags: z.array(z.string()), scores: z.array(z.number().min(0).max(100)), items: z.array(z.object({ id: z.number(), name: z.string() })) }); // Configure array generation globally const data = zocker(schema) .array({ min: 2, max: 5 }) .generate(); // Output: { // tags: ["tag1", "tag2", "tag3"], // scores: [85, 42, 67], // items: [{ id: 1, name: "Item A" }, { id: 2, name: "Item B" }] // } // Schema constraints override global options const constrainedSchema = z.object({ exactFive: z.array(z.number()).length(5), atLeastTen: z.array(z.string()).min(10) }); const constrainedData = zocker(constrainedSchema) .array({ min: 1, max: 3 }) // These are overridden by schema constraints .generate(); // exactFive will have exactly 5 elements // atLeastTen will have at least 10 elements ``` -------------------------------- ### Supply Custom Values with Zocker Source: https://github.com/lorissigrist/zocker/blob/main/README.md Use the `.supply()` method to explicitly set values for specific sub-schemas. This is useful for testing edge cases or providing known values. ```typescript const schema = z.object({ name: z.string(), age: z.number() }); const data = zocker(schema) .supply(schema.shape.name, "Jonathan") // the `name` will always be "Jonathan" .generate(); ``` -------------------------------- ### Options: .object() for ZodObject Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodObject` generator, including whether to generate extra keys. ```APIDOC ## .object Options for the built-in `z.ZodObject` generator. ### Request Body ```json { "generate_extra_keys": true; //extra keys will be generated if allowed by the schema } ``` ``` -------------------------------- ### Options: .any() / .unknown() for ZodAny/ZodUnknown Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for `z.ZodAny` and `z.ZodUnknown` generators, specifying the generation strategy. ```APIDOC ## .any / .unknown Options for the built-in `z.ZodAny` and `z.ZodUnknown` generators. ### Request Body ```json { "strategy": "true-any" | "json-compatible" | "fast"; } ``` ``` -------------------------------- ### API: .generate() Source: https://github.com/lorissigrist/zocker/blob/main/README.md Executes the data generation process based on the provided schema and returns the generated data. ```APIDOC ## .generate Executes the generation process. Returns the generated data that matches the schema provided to `zocker`. ``` -------------------------------- ### Immutable Builder Pattern for Test Reuse Source: https://context7.com/lorissigrist/zocker/llms.txt Demonstrates creating a base Zocker configuration and extending it for specific test cases without modifying the original. Methods return new instances, preserving immutability. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const userSchema = z.object({ id: z.number(), name: z.string(), email: z.email(), role: z.enum(["admin", "user", "guest"]), status: z.enum(["active", "suspended", "deleted"]) }); // Create a base configuration const baseZocker = zocker(userSchema) .setSeed(0) .array({ min: 1, max: 3 }); // Extend for specific test cases (does not modify baseZocker) test("admin user behavior", () => { const admin = baseZocker .supply(userSchema.shape.role, "admin") .generate(); expect(admin.role).toBe("admin"); }); test("suspended user behavior", () => { const suspended = baseZocker .supply(userSchema.shape.status, "suspended") .generate(); expect(suspended.status).toBe("suspended"); }); test("multiple users", () => { const users = baseZocker.generateMany(10); expect(users).toHaveLength(10); }); ``` -------------------------------- ### ZodSet Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure options for the built-in `z.ZodSet` generator, specifying minimum and maximum sizes. ```typescript { max: 10, min: 0 } ``` -------------------------------- ### Options: .array() for ZodArray Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodArray` generator, such as `min` and `max` lengths. ```APIDOC ## .array Options for the built-in `z.ZodArray` generator. ### Request Body ```json { "max": 10, "min": 0 } ``` ``` -------------------------------- ### Basic Usage: Generate Mock Data Source: https://context7.com/lorissigrist/zocker/llms.txt Use the `zocker()` function to wrap a Zod schema and generate single or multiple mock data instances. Ensure Zod is imported. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; // Define a schema const userSchema = z.object({ name: z.string(), age: z.number().min(0).max(100), email: z.email(), isActive: z.boolean(), role: z.enum(["admin", "user", "guest"]) }); // Generate a single valid user const user = zocker(userSchema).generate(); // Output: { name: "John Smith", age: 42, email: "john.smith@example.com", isActive: true, role: "user" } // Generate multiple users const users = zocker(userSchema).generateMany(5); // Output: Array of 5 valid user objects ``` -------------------------------- ### Supplying Concrete Values with .supply() Source: https://github.com/lorissigrist/zocker/blob/main/README.md Use the `.supply()` method to provide a specific value for a schema during generation. This is particularly useful for testing edge cases. The supplied value is used when a schema matching the `sub_schema` by reference is encountered. ```typescript const data = zocker(my_schema).supply(my_sub_schema, 0).generate(); ``` -------------------------------- ### API: .supply() Source: https://github.com/lorissigrist/zocker/blob/main/README.md Allows supplying a concrete value for a specific schema, useful for testing edge cases. The supplied value is used if a schema matching the `sub_schema` by reference is encountered during generation. ```APIDOC ## .supply Supply a concrete value for a specific schema. This is useful for testing edge-cases. ### Method ```typescript const data = zocker(my_schema).supply(my_sub_schema, 0).generate(); ``` The supplied value will be used if during the generation process a schema is encoutered, that matches the supplied `sub_schema` by _reference_. You can also supply a function that returns a value. The function must follow the `Generator` type. ``` -------------------------------- ### Options: .default() for ZodDefault Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodDefault` generator, controlling the chance of using the default value. ```APIDOC ## .default Options for the built-in `z.ZodDefault` generator. ### Request Body ```json { "default_chance": 0.3; } ``` ``` -------------------------------- ### Supply Custom Values for Mock Data Source: https://context7.com/lorissigrist/zocker/llms.txt Use the `.supply()` method to provide explicit values or generator functions for specific sub-schemas. This method matches schemas by reference. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ name: z.string(), age: z.number(), status: z.enum(["active", "inactive"]) }); // Supply a fixed value for the name field const data = zocker(schema) .supply(schema.shape.name, "Jonathan") .supply(schema.shape.status, "active") .generate(); // Output: { name: "Jonathan", age: 73, status: "active" } // You can also supply a generator function const nameSchema = z.string().min(2); const personSchema = z.object({ name: nameSchema, id: z.number() }); let counter = 0; const person = zocker(personSchema) .supply(nameSchema, () => `User_${counter++}`) .generate(); // Output: { name: "User_0", id: 847 } ``` -------------------------------- ### Repeatability with setSeed Source: https://github.com/lorissigrist/zocker/blob/main/README.md Ensures repeatable test data generation by specifying a seed. ```APIDOC ## Repeatability with setSeed You can specify a seed to make the generation process repeatable. This ensures that your test are never flaky. ### Method ```typescript test("my repeatable test", () => { const data = zocker(schema).setSeed(123).generate(); // always the same }); ``` We guarantee that the same seed will always produce the same data, with the same schema, same options and same version. ``` -------------------------------- ### Repeatable Data Generation with Seed Source: https://github.com/lorissigrist/zocker/blob/main/README.md Specify a seed to ensure repeatable data generation. This is crucial for making tests non-flaky, as the same seed will always produce the same data given the same schema, options, and Zocker version. ```typescript test("my repeatable test", () => { const data = zocker(schema).setSeed(123).generate(); // always the same }); ``` -------------------------------- ### Control Extra Key Generation with .object() Source: https://context7.com/lorissigrist/zocker/llms.txt Configure object generation using `.object()` to control whether extra keys are generated when the schema permits them via `.passthrough()` or `.catchall()`. Set `generate_extra_keys` to `true` to include them, or `false` to omit them. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const baseSchema = z.object({ id: z.number(), name: z.string() }).passthrough(); // Allows extra properties // Generate extra keys (default behavior) const withExtras = zocker(baseSchema) .object({ generate_extra_keys: true }) .generate(); // Output: { id: 42, name: "Alice", extra_key_1: "value", ... } // Disable extra key generation const noExtras = zocker(baseSchema) .object({ generate_extra_keys: false }) .generate(); // Output: { id: 42, name: "Alice" } ``` -------------------------------- ### Options: .number() for ZodNumber Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodNumber` generator, controlling the chance of generating extreme values. ```APIDOC ## .number Options for the built-in `z.ZodNumber` generator. ### Request Body ```json { "extreme_value_chance": 0.3; } ``` ``` -------------------------------- ### ZodObject Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure options for the built-in `z.ZodObject` generator. Set `generate_extra_keys` to true to allow generation of extra keys if permitted by the schema. ```typescript { generate_extra_keys: true; //extra keys will be generated if allowed by the schema } ``` -------------------------------- ### Options: .optional() for ZodOptional Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodOptional` generator, controlling the chance of generating `undefined`. ```APIDOC ## .optional Options for the built-in `z.ZodOptional` generator. ### Request Body ```json { "undefined_chance": 0.3; } ``` ``` -------------------------------- ### Seeded Mock Data Generation for Repeatability Source: https://context7.com/lorissigrist/zocker/llms.txt Use `.setSeed()` to make mock data generation deterministic. The same seed guarantees identical output for the same schema and options, which is crucial for reliable tests. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ name: z.string(), age: z.number(), email: z.email(), id: z.uuid() }); // Same seed = same output every time const data1 = zocker(schema).setSeed(123).generate(); const data2 = zocker(schema).setSeed(123).generate(); console.log(JSON.stringify(data1) === JSON.stringify(data2)); // true // Different seeds = different output const data3 = zocker(schema).setSeed(456).generate(); console.log(JSON.stringify(data1) === JSON.stringify(data3)); // false // Use in tests for repeatability test("my repeatable test", () => { const user = zocker(schema).setSeed(42).generate(); expect(user.age).toBeDefined(); // This test will always produce the same user data }); ``` -------------------------------- ### String Validation with Regular Expressions Source: https://github.com/lorissigrist/zocker/blob/main/README.md Zocker supports string validation using regular expressions out-of-the-box via the randexp library. For complex validation, it's recommended to encode as much logic as possible within the regex itself. ```typescript const regex_schema = z.string().regex(/^[a-z0-9]{5,10}$/); const data = zocker(regex_schema); // 1b3d5 ``` -------------------------------- ### ZodAny/ZodUnknown Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure options for `z.ZodAny` and `z.ZodUnknown` generators, selecting a generation strategy like 'true-any', 'json-compatible', or 'fast'. ```typescript { strategy: "true-any" | "json-compatible" | "fast"; } ``` -------------------------------- ### String Format Support for Zod Schemas Source: https://context7.com/lorissigrist/zocker/llms.txt Zocker automatically generates valid data for Zod's built-in string formats, including emails, UUIDs, URLs, IP addresses, dates, and custom regex patterns. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ // Standard formats email: z.email(), url: z.url(), uuid: z.uuid(), // ID formats cuid: z.cuid(), cuid2: z.cuid2(), ulid: z.ulid(), nanoid: z.nanoid(), // Network formats ipv4: z.ipv4(), ipv6: z.ipv6(), cidr: z.cidr(), // Date/time formats datetime: z.iso.datetime(), date: z.iso.date(), time: z.iso.time(), // Custom regex phoneNumber: z.string().regex(/^\+1-\d{3}-\d{3}-\d{4}$/), postalCode: z.string().regex(/^[A-Z]{2}\d{5}$/) }); const data = zocker(schema).generate(); // Output: // { // email: "john.doe@example.com", // url: "https://example.org/path", // uuid: "550e8400-e29b-41d4-a716-446655440000", // cuid: "cjld2cyuq0000t3rmniod1foy", // cuid2: "tz4a98xxat96iws9zmbrgj3a", // ulid: "01ARZ3NDEKTSV4RRFFQ69G5FAV", // nanoid: "V1StGXR8_Z5jdHi6B-myT", // ipv4: "192.168.1.1", // ipv6: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", // cidr: "10.0.0.0/24", // datetime: "2024-03-15T14:30:00.000Z", // date: "2024-03-15", // time: "14:30:00", // phoneNumber: "+1-555-123-4567", // postalCode: "CA90210" // } ``` -------------------------------- ### ZodDefault Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure the `default_chance` for the `z.ZodDefault` generator to control the probability of using the default value. ```typescript { default_chance: 0.3; } ``` -------------------------------- ### Manage Optional/Nullable Field Probabilities Source: https://context7.com/lorissigrist/zocker/llms.txt Control the probability of optional fields returning `undefined` and nullable fields returning `null` using `.optional()` and `.nullable()`. Set `undefined_chance` or `null_chance` to 0 to always generate a value, or to 1 to always generate `undefined`/`null`. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ name: z.string(), nickname: z.string().optional(), middleName: z.string().nullable(), bio: z.string().nullish() // optional and nullable }); // Default: 30% chance of undefined/null const data1 = zocker(schema).generate(); // Always generate values (never undefined) const fullData = zocker(schema) .optional({ undefined_chance: 0 }) .nullable({ null_chance: 0 }) .generate(); // Output: All fields will have string values // Always generate undefined/null for optional/nullable fields const sparseData = zocker(schema) .optional({ undefined_chance: 1 }) .nullable({ null_chance: 1 }) .generate(); // Output: { name: "John", nickname: undefined, middleName: null, bio: undefined } ``` -------------------------------- ### Options: .nullable() for ZodNullable Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configures options for the built-in `z.ZodNullable` generator, controlling the chance of generating `null`. ```APIDOC ## .nullable Options for the built-in `z.ZodNullable` generator. ### Request Body ```json { "null_chance": 0.3; } ``` ``` -------------------------------- ### ZodNumber Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure the `extreme_value_chance` for the `z.ZodNumber` generator to control the probability of generating extreme numerical values. ```typescript { extreme_value_chance: 0.3; } ``` -------------------------------- ### API: .setSeed() Source: https://github.com/lorissigrist/zocker/blob/main/README.md Sets the seed for the random number generator to ensure repeatable data generation. If no seed is set, a random one is chosen. ```APIDOC ## .setSeed Set the seed for the random number generator. This ensures that the generation process is repeatable. If you don't set a seed, a random one will be chosen. ``` -------------------------------- ### Setting Generation Depth Limit Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure the maximum depth for generating cyclic data structures using the `.setDepthLimit()` method. The default limit is 5. ```typescript zocker(schema).setDepthLimit(10).generate(); ``` -------------------------------- ### API: .setDepthLimit() Source: https://github.com/lorissigrist/zocker/blob/main/README.md Sets the maximum depth for generating cyclic data structures. Defaults to 5. ```APIDOC ## .setDepthLimit Set the maximum depth of cyclic data. Defaults to 5. ``` -------------------------------- ### ZodNullable Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure the `null_chance` for the `z.ZodNullable` generator to control the probability of generating a null value. ```typescript { null_chance: 0.3; } ``` -------------------------------- ### ZodOptional Generator Options Source: https://github.com/lorissigrist/zocker/blob/main/README.md Configure the `undefined_chance` for the `z.ZodOptional` generator to control the probability of generating an undefined value. ```typescript { undefined_chance: 0.3; } ``` -------------------------------- ### Control Default Value Probability with .default() Source: https://context7.com/lorissigrist/zocker/llms.txt Adjust the likelihood that fields with `.default()` will use their default value instead of generating a new one. Set `default_chance` to 1 to always use defaults, or 0 to never use them. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ name: z.string(), role: z.string().default("user"), active: z.boolean().default(true) }); // 30% chance of using default (default behavior) const data1 = zocker(schema).generate(); // Always use defaults const defaults = zocker(schema) .default({ default_chance: 1 }) .generate(); // Output: { name: "John", role: "user", active: true } // Never use defaults const noDefaults = zocker(schema) .default({ default_chance: 0 }) .generate(); // Output: { name: "John", role: "generated_string", active: false } ``` -------------------------------- ### Override Built-in Mock Data Generators Source: https://context7.com/lorissigrist/zocker/llms.txt Replace default generators for entire schema categories (like numbers or strings) using `.override()`. You can pass the Zod class or a string name of the type. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ name: z.string(), age: z.number(), score: z.number().min(0).max(100) }); // Override all numbers to return 42 const data1 = zocker(schema) .override("number", 42) .generate(); // Output: { name: "Alice Brown", age: 42, score: 42 } // Override with a function that has access to the schema const data2 = zocker(schema) .override(z.ZodNumber, (numberSchema, ctx) => { // Return 0 if the schema has a minimum constraint, otherwise 1 const hasMin = numberSchema._zod.def.checks?.some( (check) => check._zod.def.value !== undefined ); return hasMin ? 0 : 1; }) .generate(); // Output: { name: "Bob Johnson", age: 1, score: 0 } ``` -------------------------------- ### API: .override() Source: https://github.com/lorissigrist/zocker/blob/main/README.md Overrides the generator for an entire category of schemas, such as `z.ZodNumber`. You can provide the schema class or the datatype name as a string. ```APIDOC ## .override Overrides the generator for an entire category of schemas. This is useful if you want to override the generation of `z.ZodNumber` for example. ### Method ```typescript const data = zocker(my_schema).override(z.$ZodNumber, 0).generate(); ``` The supplied value will be used if during the generation process a schema is encoutered, that is an _instance_ of the supplied `schema`. Alternatively, you can also provide the name of the datatype you want to override as a string. (e.g `"number"`). Intellisense will help you out here. You can also supply a function that returns a value. The function must follow the `Generator` type. ``` -------------------------------- ### Control Number Generation with .number() Source: https://context7.com/lorissigrist/zocker/llms.txt Influence number generation using `.number()`, particularly with `extreme_value_chance`. Set this to a higher value (e.g., 0.8) to increase the likelihood of generating boundary values, or to a lower value (e.g., 0.1) for more typical values within the defined range. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; const schema = z.object({ temperature: z.number().min(-40).max(50), percentage: z.number().min(0).max(100), score: z.number().int().min(0).max(1000) }); // Increase chance of hitting boundary values (useful for edge case testing) const edgeCaseData = zocker(schema) .number({ extreme_value_chance: 0.8 }) .generate(); // More likely to get values like -40, 50, 0, 100, 0, 1000 // Reduce extreme values for more "normal" looking data const normalData = zocker(schema) .number({ extreme_value_chance: 0.1 }) .generate(); // More likely to get values in the middle of ranges ``` -------------------------------- ### Overriding Generators with .override() Source: https://github.com/lorissigrist/zocker/blob/main/README.md The `.override()` method allows you to replace the default generator for a category of schemas, such as `z.ZodNumber`. This can be done by providing the schema class or its string name. A function conforming to the `Generator` type can also be supplied. ```typescript const data = zocker(my_schema).override(z.$ZodNumber, 0).generate(); ``` -------------------------------- ### Control Recursion Depth with .setDepthLimit() Source: https://context7.com/lorissigrist/zocker/llms.txt Use `.setDepthLimit()` to manage the maximum recursion depth for Zocker when generating data from cyclic or recursive schemas defined with `z.lazy()`. The default limit is 5. ```typescript import { z } from "zod/v4"; import { zocker } from "zocker"; // Define a recursive Person schema const personSchema = z.object({ name: z.string(), children: z.array(z.lazy(() => personSchema)).default([]) }); // Generate with default depth limit (5) const family = zocker(personSchema).generate(); // Generate with custom depth limit const shallowFamily = zocker(personSchema) .setDepthLimit(2) .generate(); // JSON recursive schema example const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]); const jsonSchema = z.lazy(() => z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)]) ); const jsonData = zocker(jsonSchema) .setDepthLimit(3) .generate(); // Output: Nested JSON structure up to 3 levels deep ``` -------------------------------- ### Override Zocker Built-in Generators Source: https://github.com/lorissigrist/zocker/blob/main/README.md Override built-in generators using the `.override()` method. Pass a schema and a value or function to generate values for matching schemas. The function receives the schema and a generation context. ```typescript const data = zocker(my_schema).override(z.ZodNumber, Infinity).generate(); ``` ```typescript const data = zocker(my_schema) .override(z.ZodNumber, (schema, _ctx) => { //Example: Return 0 if there is a minimum specified, and 1 if there isn't if (schema._def.checks.some((check) => check.kind == "min")) return 0; return 1; }) .generate(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.