|
1
|
import { zodResolver } from "@hookform/resolvers/zod" |
|
2
|
import { describe, expect, it } from "vitest" |
|
3
|
import { z } from "zod" |
|
4
|
|
|
5
|
/** |
|
6
|
* `@hookform/resolvers` and `zod` have to stay on compatible majors. |
|
7
|
* |
|
8
|
* Resolvers v3 detects a validation failure by checking `error.errors`, which |
|
9
|
* only exists on zod v3 errors. Pairing it with zod v4 (where the issues moved |
|
10
|
* to `error.issues`) makes the resolver re-throw the ZodError instead of |
|
11
|
* returning it, so react-hook-form never populates `formState.errors` and every |
|
12
|
* form in the dashboard silently refuses to submit with no visible feedback. |
|
13
|
* |
|
14
|
* These tests fail loudly if that pairing regresses. |
|
15
|
*/ |
|
16
|
describe("zodResolver <> zod compatibility", () => { |
|
17
|
const resolverOptions = { |
|
18
|
shouldUseNativeValidation: false, |
|
19
|
fields: {}, |
|
20
|
} as any |
|
21
|
|
|
22
|
it("returns validation errors instead of throwing", async () => { |
|
23
|
const schema = z.object({ |
|
24
|
region_id: z.string().min(1), |
|
25
|
}) |
|
26
|
|
|
27
|
const result = await zodResolver(schema)( |
|
28
|
{ region_id: "" }, |
|
29
|
undefined, |
|
30
|
resolverOptions |
|
31
|
) |
|
32
|
|
|
33
|
expect(result.errors).toHaveProperty("region_id") |
|
34
|
expect(result.errors.region_id?.message).toBeTruthy() |
|
35
|
}) |
|
36
|
|
|
37
|
it("surfaces messages added by superRefine", async () => { |
|
38
|
const schema = z |
|
39
|
.object({ |
|
40
|
customer_id: z.string().optional(), |
|
41
|
email: z.union([z.literal(""), z.string().email()]).optional(), |
|
42
|
}) |
|
43
|
.superRefine((data, ctx) => { |
|
44
|
if (!data.customer_id && !data.email) { |
|
45
|
ctx.addIssue({ |
|
46
|
code: "custom", |
|
47
|
message: "Either a customer or email must be provided", |
|
48
|
path: ["email"], |
|
49
|
}) |
|
50
|
} |
|
51
|
}) |
|
52
|
|
|
53
|
const result = await zodResolver(schema)( |
|
54
|
{ customer_id: "", email: "" }, |
|
55
|
undefined, |
|
56
|
resolverOptions |
|
57
|
) |
|
58
|
|
|
59
|
expect(result.errors.email?.message).toBe( |
|
60
|
"Either a customer or email must be provided" |
|
61
|
) |
|
62
|
}) |
|
63
|
|
|
64
|
it("resolves with no errors for a valid payload", async () => { |
|
65
|
const schema = z.object({ region_id: z.string().min(1) }) |
|
66
|
|
|
67
|
const result = await zodResolver(schema)( |
|
68
|
{ region_id: "reg_1" }, |
|
69
|
undefined, |
|
70
|
resolverOptions |
|
71
|
) |
|
72
|
|
|
73
|
expect(result.errors).toEqual({}) |
|
74
|
expect(result.values).toEqual({ region_id: "reg_1" }) |
|
75
|
}) |
|
76
|
}) |