-
-
Notifications
You must be signed in to change notification settings - Fork 144
/
zod.ts
88 lines (72 loc) 路 2.48 KB
/
zod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
});
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: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
};
const result = await zodResolver(schema)(data);
expect(result).toEqual({ errors: {}, values: data });
});
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: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
};
const result = await zodResolver(schema, undefined, { mode: 'sync' })(data);
expect(result).toEqual({ errors: {}, values: data });
});
it('should return a single error from zodResolver when validation fails', async () => {
const data = {
password: '___',
email: '',
birthYear: 'birthYear',
};
const result = await zodResolver(schema)(data);
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 result = await zodResolver(schema, undefined, { mode: 'sync' })(data);
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, true);
expect(result).toMatchSnapshot();
});
});