forked from colinhacks/zod
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathall-errors.test.ts
90 lines (84 loc) · 1.98 KB
/
all-errors.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
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
89
90
// @ts-ignore TS6133
import { expect, test } from "@jest/globals";
import * as z from "../index";
test("all errors", () => {
const propertySchema = z.string();
const schema = z
.object({
a: propertySchema,
b: propertySchema,
})
.refine(
(val) => {
return val.a === val.b;
},
{ message: "Must be equal" }
);
try {
schema.parse({
a: "asdf",
b: "qwer",
});
} catch (error) {
if (error instanceof z.ZodError) {
expect(error.flatten()).toEqual({
formErrors: ["Must be equal"],
fieldErrors: {},
});
}
}
try {
schema.parse({
a: null,
b: null,
});
} catch (_error) {
const error = _error as z.ZodError;
expect(error.flatten()).toEqual({
formErrors: [],
fieldErrors: {
a: ["Expected string, received null"],
b: ["Expected string, received null"],
},
});
expect(error.flatten((iss) => iss.message.toUpperCase())).toEqual({
formErrors: [],
fieldErrors: {
a: ["EXPECTED STRING, RECEIVED NULL"],
b: ["EXPECTED STRING, RECEIVED NULL"],
},
});
// Test identity
expect(error.flatten((i: z.ZodIssue) => i)).toEqual({
formErrors: [],
fieldErrors: {
a: [
{
code: "invalid_type",
expected: "string",
message: "Expected string, received null",
path: ["a"],
received: "null",
},
],
b: [
{
code: "invalid_type",
expected: "string",
message: "Expected string, received null",
path: ["b"],
received: "null",
},
],
},
});
// Test mapping
expect(error.flatten((i: z.ZodIssue) => i.message.length)).toEqual({
formErrors: [],
fieldErrors: {
a: ["Expected string, received null".length],
b: ["Expected string, received null".length],
},
});
}
});