npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

zod-fast-check-patched

v0.10.2

Published

Generate fast-check arbitraries from Zod schemas. Patched to newer zod version. Forked from DavidTimms.

Downloads

33

Readme

zod-fast-check

A small library to automatically derive fast-check arbitraries from schemas defined using the validation library Zod. These enables easy and thorough property-based testing.

Why this fork?

Some incompatibility when using this (great) library with newer Zod versions, this is a minimal viable patch that fixes the issues I encounter. Happy to include your suggestions! Just create a PR 😊

Usage

Here is a complete example using Jest.

import * as z from 'zod';
import * as fc from 'fast-check';
import { ZodFastCheck } from 'zod-fast-check';

// Define a Zod schema
const User = z.object({
  firstName: z.string(),
  lastName: z.string(),
});

// Define an operation using the data type
function fullName(user: unknown): string {
  const parsedUser = User.parse(user);
  return `${parsedUser.firstName} ${parsedUser.lastName}`;
}

// Create an arbitrary which generates valid inputs for the schema
const userArbitrary = ZodFastCheck().inputOf(User);

// Use the arbitrary in a property-based test
test("User's full name always contains their first and last names", () =>
  fc.assert(
    fc.property(userArbitrary, (user) => {
      const name = fullName(user);
      expect(name).toContain(user.firstName);
      expect(name).toContain(user.lastName);
    })
  ));

The main interface is the ZodFastCheck class, which has the following methods:

inputOf

inputOf<Input>(zodSchema: ZodSchema<unknown, ZodTypeDef, Input>): Arbitrary<Input>

Creates an arbitrary which will generate values which are valid inputs to the schema. This should be used for testing functions which use the schema for validation.

outputOf

outputOf<Output>(zodSchema: ZodSchema<Output, ZodTypeDef, unknown>): Arbitrary<Output>

Creates an arbitrary which will generate values which are valid outputs of parsing the schema. This means any transformations have already been applied to the values. This should be used for testing functions which do not use the schema directly, but use data parsed by the schema.

override

override<Input>(schema: ZodSchema<unknown, ZodTypeDef, Input>, arbitrary: Arbitrary<Input>): ZodFastCheck

Returns a new ZodFastCheck instance which will use the provided arbitrary when generating inputs for the given schema. This includes if the schema is used as a component of a larger schema.

For example, if we have a schema which validates that a string has a prefix, we can define an override to produce valid values.

const WithFoo = z.string().regex(/^foo/);

const zodFastCheck = ZodFastCheck().override(
  WithFoo,
  fc.string().map((s) => 'foo' + s)
);

const arbitrary = zodFastCheck.inputOf(z.array(WithFoo));

Schema overrides are matched based on object identity, so you need to define the override using the exact schema object, rather than an equivalent schema.

If you need to use zod-fast-check to generate the override, it is easy to end up with a circular dependency. You can avoid this by defining the override lazily using a function. This function is called with the ZodFastCheck instance as an argument.

const WithFoo = z.string().regex(/^foo/);

const zodFastCheck = ZodFastCheck().override(WithFoo, (zfc) =>
  zfc.inputOf(z.string()).map((s) => 'foo' + s)
);

const arbitrary = zodFastCheck.inputOf(z.array(WithFoo));

Supported Zod Schema Features

Data types

✅ string (including email, datetime, UUID and URL)
✅ number
✅ nan
✅ bigint
✅ boolean
✅ date
✅ undefined
✅ null
✅ symbol ✅ array
✅ object
✅ union
✅ discriminated union
✅ tuple
✅ record
✅ map
✅ set
✅ function
✅ literal
✅ enum
✅ nativeEnum
✅ promise
✅ any
✅ unknown
✅ void
✅ optional
✅ nullable
✅ default
✅ branded types
✅ transforms
✅ refinements (see below)
✅ pipe
✅ catch
❌ intersection
❌ lazy
❌ never

Refinements

Refinements are supported, but they are produced by filtering the original arbitrary by the refinement function. This means that for refinements which have a very low probability of matching a random input, it will not be able to generate valid values. This is most common when using refinements to check that a string matches a particular format. If this occurs, it will throw a ZodFastCheckGenerationError.

In cases like this, it is recommended to define an override for the problematic subschema.