Skip to content

Saeris/valimock

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

123 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸƒ Valimock

npm version CI status

Generate mock data for Valibot schemas using Faker


πŸ“¦ Installation

npm install --save-dev valimock @faker-js/faker
yarn add -D valimock @faker-js/faker

Note

Tested against valibot >= 1.4.0 and @faker-js/faker >= 10.0.0. Older versions of either may still work β€” the peer-dependency ranges remain permissive β€” but the test matrix runs against current majors.

πŸ”§ Usage

Import and optionally configure a new instance of the Valimock class, then pass along your valibot schema to mock(), that's it!

import { parse, array, union, string, pipe, url, number, maxValue } from "valibot";
import { Valimock } from "valimock";

describe(`example test`, () => {
  it(`should generate valid mock data`, () => {
    const schema = array(union([pipe(string(), url()), pipe(number(), maxValue(20))]));
    const result = new Valimock().mock(schema);
    expect(parse(schema, result)).toStrictEqual(result);
  });
});

Note

For async schemas, you will need to use parseAsync(). Be aware that async schemas generate a Promise and may need to be await'ed depending on usage.

Please see the __tests__ folder for more usage examples of different schema types.

Configuration

new Valimock(options) accepts a partial options object:

option type default purpose
faker Faker default Faker instance Faker instance used for all generation; supply your own to control locale or seeding centrally
seed number | number[] undefined Re-seeds Faker on every mock() call for deterministic output
stringMap Record<string, () => string> undefined Per-key string overrides (when generating strings inside an object). Wins over the built-in format/key-name routing.
customMocks Record<string, (schema) => unknown> {} Generators for Valibot schema types Valimock doesn't yet support. Keyed by schema.type.
recordKeysLength number 1 How many entries to generate for a record() schema
mapEntriesLength number 1 How many entries to generate for a map() schema
throwOnUnknownType boolean false When true, throw a MockError for unrecognized schema types instead of warning
onWarn (message: string) => void console.warn Diagnostic sink. Receives unhandled-action notices, retry-budget exhaustion, and generation errors. Set to () => {} to silence.
mockeryMapper MockeryMapper built-in defaults Deprecated. Prefer stringMap or contributing an action handler. Still consulted for backwards compatibility; emits a one-time warning when invoked.

API Coverage

Valimock's string mocking is built around a small pipeline (src/schemas/string/) with a per-action registry. Adding support for a new Valibot action is a one-line addition to the registry. See Contributing below.

Any schema type Valimock doesn't yet support can be handled by supplying a customMocks entry keyed by the schema's type field. When Valimock has no built-in mocker and no matching customMocks entry (notably for v.custom(...)), it emits an onWarn notice and returns undefined rather than silently producing an invalid value. Set throwOnUnknownType: true to turn that into a thrown MockError.

Schemas

Any Array Bigint Blob Boolean Custom Date
βœ” βœ” βœ” βœ” βœ” βž– βœ”
Enum ExactOptional File Function Instance Intersect Lazy
βœ” βœ” βœ” βœ” βœ” βœ” βœ”
Literal LooseObject LooseTuple Map NaN Never Null
βœ” βœ” βœ” βœ” βœ” βœ” βœ”
Nullable Nullish NonNullable NonNullish NonOptional Number Object
βœ” βœ” βœ” βœ” βœ” βœ” βœ”
ObjectWithRest Optional Picklist Promise Record Set StrictObject
βœ” βœ” βœ” βœ” βœ” βœ” βœ”
StrictTuple String Symbol Tuple TupleWithRest Undefined Undefinedable
βœ” βœ” βœ” βœ” βœ” βœ” βœ”
Union Unknown Variant Void
βœ” βœ” βœ” βœ”

Legend: βœ” implemented Β· ⚠ partial Β· ❌ not implemented Β· βž– user-supplied via customMocks

custom schemas run an arbitrary user predicate that Valimock has no general way to satisfy. Provide a matching customMocks entry keyed by the schema's type ("custom", or a more specific tag if you wrap multiple custom() calls in a brand) to produce a value that will pass the predicate.

For environment-dependent schemas (blob, file, function, promise, instance), Valimock returns a structural placeholder when the relevant global isn't available (e.g. Blob / File outside Node β‰₯18 / browsers / jsdom). The onWarn sink surfaces a notice in those cases.

Validations

Array

empty includes length maxLength minLength nonEmpty
βœ” ❌ βœ” βœ” βœ” βœ”

Set

size minSize maxSize notSize
βœ” βœ” βœ” βœ”

BigInt

gtValue ltValue maxValue minValue value values
βœ” βœ” βœ” βœ” βœ” βœ”

Date

maxValue minValue value
βœ” βœ” βœ”

Number

finite gtValue integer ltValue maxValue minValue multipleOf notValue notValues safeInteger value values
βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ”

String

base64 bic bytes creditCard cuid2 decimal digits domain email emoji empty endsWith excludes
βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ”
graphemes hash hexColor hexadecimal imei includes ip ipv4 ipv6 isbn isoDate isoDateTime isoDateTimeSecond
βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ”
isoTime isoTimeSecond isoTimestamp isoWeek isrc jwsCompact length mac mac48 mac64 maxBytes maxGraphemes maxLength
βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ”
maxWords minBytes minGraphemes minLength minWords nanoid nonEmpty notBytes notGraphemes notLength notValue notValues notWords
βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ”
octal regex rfcEmail slug startsWith ulid url uuid value values words
βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ” βœ”

Not yet implemented (string): notEntries. The bytes / graphemes / words families currently treat each unit as .length (correct for ASCII output, approximate for multi-byte content); a future enhancement may distinguish them via Intl.Segmenter.

When Valimock encounters an action it doesn't know how to handle inside a string pipe, it emits an onWarn notice and ignores the action β€” the generated value satisfies the rest of the constraints but may not match the unhandled one. Override options.onWarn to route those notices into your test reporter or set throwOnUnknownType: true for strict mode.

🀝 Contributing

The project uses Vite+ as a unified toolchain (Oxlint + Oxfmt

  • tsdown + Vitest) and Bumpy for versioning and release.
vp install           # install dependencies
vp check --fix       # format + lint + typecheck (with autofixes)
vp test              # run Vitest
yarn bumpy add       # create a bump file for your PR

Adding support for a new Valibot string action is typically a two-line change: register a handler in src/schemas/string/actionHandlers.ts and (if the action is a format selector) add the matching generator to src/schemas/string/formatGenerators.ts. The property-based block in src/__tests__/mockString.spec.ts will exercise the new combination automatically once the action appears in its formats table.

πŸ“£ Acknowledgements

Valimock's implementation is based on @anatine/zod-mock

πŸ₯‚ License

Released under the MIT license Β© Drake Costa.

About

πŸƒ Generate mock data for Valibot schemas using Faker

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Contributors