Custom Jest matchers to help validate Zod schemas and to prevent having a lot of boilerplate
Basic Usage | API | Installation | License
First, add the custom matchers to Jest. A convenient way to do this is via a setup file included in setupFilesAfterEnv
:
import {getJestZodMatchers} from 'jest-zod-matchers';
expect.extend(getJestZodMatchers());
Now you can use the custom matchers in your tests:
expect(safeParsedZodObjectSchema).toBeValidZodObject({foo: 'bar'});
expect(safeParsedZodSchema).toThrowZodError('Zod error');
Validates a safe parsed Zod schema and checks whether or not it's the expected successful result.
-
zodOutputObject
- Optional An object expecting key/value pairs. IfzodOutputObject
is not provided, the parsed result should at least be valid. IfzodOutputObject
is provided, it will check if all the given keys exist and if their values match the parsed result.
expect(safeParsedZodObjectSchema).toBeValidZodObject(); // expects a valid parse result
expect(safeParsedZodObjectSchema).toBeValidZodObject({foo: 'bar'}); // expects "foo" to be available in the parsed result and its value be a string of "bar"
Expects a safe parsed Zod schema to throw at least one error. If at least one is thrown, the first error will be tested.
-
expectedErrorMessage
- Optional An error string. IfexpectedErrorMessage
is not provided, the parsed result should at least throw any error. IfexpectedErrorMessage
is provided, it will check if the first thrown error matches the value ofexpectedErrorMessage
.
npm install -D jest-zod-matchers
MIT