Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zod fix union error + reduce resolver size #126

Merged
merged 2 commits into from
Feb 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ module.exports = {
restoreMocks: true,
testMatch: ['**/__tests__/**/*.+(js|jsx|ts|tsx)'],
transformIgnorePatterns: ['[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$'],
testPathIgnorePatterns: ['/__fixtures__/'],
moduleNameMapper: {
'^@hookform/resolvers$': '<rootDir>/src',
},
Expand Down
48 changes: 48 additions & 0 deletions zod/src/__tests__/__fixtures__/data.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as z from 'zod';

export const schema = z
.object({
username: z.string().regex(/^\w+$/).min(3).max(30),
password: z.string().regex(/^[a-zA-Z0-9]{3,30}/),
repeatPassword: z.string(),
accessToken: z.union([z.string(), z.number()]).optional(),
birthYear: z.number().min(1900).max(2013).optional(),
email: z.string().email().optional(),
tags: z.array(z.string()),
enabled: z.boolean(),
like: z
.array(
z.object({
id: z.number(),
name: z.string().length(4),
}),
)
.optional(),
})
.refine((data) => data.password === data.repeatPassword, {
message: "Passwords don't match",
path: ['confirm'], // set path of error
});

export const validData: z.infer<typeof schema> = {
username: 'Doe',
password: 'Password123',
repeatPassword: 'Password123',
birthYear: 2000,
email: '[email protected]',
tags: ['tag1', 'tag2'],
enabled: true,
like: [
{
id: 1,
name: 'name',
},
],
};

export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
};
78 changes: 78 additions & 0 deletions zod/src/__tests__/__snapshots__/zod.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ Object {
"message": "Required",
"type": "invalid_type",
},
"like": Object {
"0": Object {
"id": Object {
"message": "Expected number, received string",
"type": "invalid_type",
},
"name": Object {
"message": "Required",
"type": "invalid_type",
},
},
"message": "Invalid input",
"type": "invalid_union",
},
"password": Object {
"message": "Invalid",
"type": "invalid_string",
Expand Down Expand Up @@ -59,6 +73,20 @@ Object {
"message": "Required",
"type": "invalid_type",
},
"like": Object {
"0": Object {
"id": Object {
"message": "Expected number, received string",
"type": "invalid_type",
},
"name": Object {
"message": "Required",
"type": "invalid_type",
},
},
"message": "Invalid input",
"type": "invalid_union",
},
"password": Object {
"message": "Invalid",
"type": "invalid_string",
Expand Down Expand Up @@ -87,6 +115,7 @@ Object {
"message": "Invalid input",
"type": "invalid_union",
"types": Object {
"invalid_type": "Expected undefined, received string",
"invalid_union": "Invalid input",
},
},
Expand All @@ -111,6 +140,30 @@ Object {
"invalid_type": "Required",
},
},
"like": Object {
"0": Object {
"id": Object {
"message": "Expected number, received string",
"type": "invalid_type",
"types": Object {
"invalid_type": "Expected number, received string",
},
},
"name": Object {
"message": "Required",
"type": "invalid_type",
"types": Object {
"invalid_type": "Required",
},
},
},
"message": "Invalid input",
"type": "invalid_union",
"types": Object {
"invalid_type": "Expected undefined, received array",
"invalid_union": "Invalid input",
},
},
"password": Object {
"message": "Invalid",
"type": "invalid_string",
Expand Down Expand Up @@ -151,6 +204,7 @@ Object {
"message": "Invalid input",
"type": "invalid_union",
"types": Object {
"invalid_type": "Expected undefined, received string",
"invalid_union": "Invalid input",
},
},
Expand All @@ -175,6 +229,30 @@ Object {
"invalid_type": "Required",
},
},
"like": Object {
"0": Object {
"id": Object {
"message": "Expected number, received string",
"type": "invalid_type",
"types": Object {
"invalid_type": "Expected number, received string",
},
},
"name": Object {
"message": "Required",
"type": "invalid_type",
"types": Object {
"invalid_type": "Required",
},
},
},
"message": "Invalid input",
"type": "invalid_union",
"types": Object {
"invalid_type": "Expected undefined, received array",
"invalid_union": "Invalid input",
},
},
"password": Object {
"message": "Invalid",
"type": "invalid_string",
Expand Down
94 changes: 17 additions & 77 deletions zod/src/__tests__/zod.ts
Original file line number Diff line number Diff line change
@@ -1,108 +1,54 @@
import * as z from 'zod';
import { zodResolver } from '..';

const schema = z
.object({
username: z.string().regex(/^\w+$/).min(3).max(30),
password: z.string().regex(/^[a-zA-Z0-9]{3,30}/),
repeatPassword: z.string(),
accessToken: z.union([z.string(), z.number()]).optional(),
birthYear: z.number().min(1900).max(2013).optional(),
email: z.string().email().optional(),
tags: z.array(z.string()),
enabled: z.boolean(),
})
.refine((data) => data.password === data.repeatPassword, {
message: "Passwords don't match",
path: ['confirm'], // set path of error
});
import { schema, validData, invalidData } from './__fixtures__/data';

describe('zodResolver', () => {
it('should return values from zodResolver when validation pass', async () => {
const data: z.infer<typeof schema> = {
username: 'Doe',
password: 'Password123',
repeatPassword: 'Password123',
birthYear: 2000,
email: '[email protected]',
tags: ['tag1', 'tag2'],
enabled: true,
};

const parseAsyncSpy = jest.spyOn(schema, 'parseAsync');

const result = await zodResolver(schema)(data, undefined, { fields: {} });
const result = await zodResolver(schema)(validData, undefined, {
fields: {},
});

expect(parseAsyncSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: data });
expect(result).toEqual({ errors: {}, values: validData });
});

it('should return values from zodResolver with `mode: sync` when validation pass', async () => {
const data: z.infer<typeof schema> = {
username: 'Doe',
password: 'Password123',
repeatPassword: 'Password123',
birthYear: 2000,
email: '[email protected]',
tags: ['tag1', 'tag2'],
enabled: true,
};

const parseSpy = jest.spyOn(schema, 'parse');
const parseAsyncSpy = jest.spyOn(schema, 'parseAsync');

const result = await zodResolver(schema, undefined, { mode: 'sync' })(
data,
undefined,
{ fields: {} },
);
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields: {} });

expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: data });
expect(result).toEqual({ errors: {}, values: validData });
});

it('should return a single error from zodResolver when validation fails', async () => {
const data = {
password: '___',
email: '',
birthYear: 'birthYear',
};

const result = await zodResolver(schema)(data, undefined, { fields: {} });
const result = await zodResolver(schema)(invalidData, undefined, {
fields: {},
});

expect(result).toMatchSnapshot();
});

it('should return a single error from zodResolver with `mode: sync` when validation fails', async () => {
const data = {
password: '___',
email: '',
birthYear: 'birthYear',
};

const parseSpy = jest.spyOn(schema, 'parse');
const parseAsyncSpy = jest.spyOn(schema, 'parseAsync');

const result = await zodResolver(schema, undefined, { mode: 'sync' })(
data,
undefined,
{ fields: {} },
);
const result = await zodResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields: {} });

expect(parseSpy).toHaveBeenCalledTimes(1);
expect(parseAsyncSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});

it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const data = {
password: '___',
email: '',
birthYear: 'birthYear',
};

const result = await zodResolver(schema)(data, undefined, {
const result = await zodResolver(schema)(invalidData, undefined, {
fields: {},
criteriaMode: 'all',
});
Expand All @@ -111,14 +57,8 @@ describe('zodResolver', () => {
});

it('should return all the errors from zodResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const data = {
password: '___',
email: '',
birthYear: 'birthYear',
};

const result = await zodResolver(schema, undefined, { mode: 'sync' })(
data,
invalidData,
undefined,
{
fields: {},
Expand Down
2 changes: 1 addition & 1 deletion zod/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { ParseParams } from 'zod/lib/src/parser';
export type Resolver = <T extends z.ZodSchema<any, any>>(
schema: T,
schemaOptions?: ParseParams,
factoryOptions?: { mode: 'async' | 'sync' },
factoryOptions?: { mode?: 'async' | 'sync' },
) => <TFieldValues extends FieldValues, TContext>(
values: UnpackNestedValue<TFieldValues>,
context: TContext | undefined,
Expand Down
Loading