forked from colinhacks/zod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefine.test.ts
51 lines (45 loc) · 1.4 KB
/
refine.test.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
import * as z from '../index';
test('refinement', () => {
const obj1 = z.object({
first: z.string(),
second: z.string(),
});
const obj2 = obj1.partial();
const obj3 = obj2.refine(data => data.first || data.second, 'Either first or second should be filled in.');
expect(obj1 === (obj2 as any)).toEqual(false);
expect(obj2 === obj3).toEqual(false);
expect(() => obj1.parse({})).toThrow();
expect(() => obj2.parse({ third: 'adsf' })).toThrow();
expect(() => obj3.parse({})).toThrow();
obj3.parse({ first: 'a' });
obj3.parse({ second: 'a' });
obj3.parse({ first: 'a', second: 'a' });
});
test('refinement 2', () => {
const validationSchema = z
.object({
email: z.string().email(),
password: z.string(),
confirmPassword: z.string(),
})
.refine(data => data.password === data.confirmPassword, 'Both password and confirmation must match');
expect(() =>
validationSchema.parse({
email: '[email protected]',
password: 'aaaaaaaa',
confirmPassword: 'bbbbbbbb',
}),
).toThrow();
});
test('custom path', () => {
z.object({
password: z.string(),
confirm: z.string(),
})
.refine(data => data.confirm === data.password, { path: ['confirm'] })
.parseAsync({ password: 'asdf', confirm: 'qewr' })
.catch(err => {
console.log(JSON.stringify(err, null, 2));
expect(err.errors[0].path).toEqual(['confirm']);
});
});