forked from mattpocock/zod-fetch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
createZodFetcher.test.ts
107 lines (92 loc) · 2.43 KB
/
createZodFetcher.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { afterAll, afterEach, beforeAll, expect, it } from "vitest";
import { rest } from "msw";
import { setupServer } from "msw/node";
import "isomorphic-fetch";
import { createZodFetcher } from ".";
import { z, ZodError } from "zod";
const server = setupServer();
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it("Should create a default fetcher", async () => {
server.use(
rest.get("https://example.com", (req, res, ctx) => {
return res(ctx.json({ hello: "world" }), ctx.status(200));
}),
);
const fetchWithZod = createZodFetcher();
const response = await fetchWithZod(
z.object({
hello: z.string(),
}),
"https://example.com",
);
expect(response).toEqual({
hello: "world",
});
});
it("Should throw an error with mis-matched schemas with a default fetcher", async () => {
server.use(
rest.get("https://example.com", (req, res, ctx) => {
return res(ctx.json({ hello: "world" }), ctx.status(200));
}),
);
const fetchWithZod = createZodFetcher();
await expect(
fetchWithZod(
z.object({
hello: z.number(),
}),
"https://example.com",
),
).rejects.toMatchObject(
ZodError.create([
{
code: "invalid_type",
expected: "number",
received: "string",
path: ["hello"],
message: "Expected number, received string",
},
]),
);
});
it("Should throw an error if response is not ok with the default fetcher", async () => {
server.use(
rest.get("https://example.com", (req, res, ctx) => {
return res(
ctx.json({
error: "Invalid permissions",
}),
ctx.status(403),
);
}),
);
const fetchWithZod = createZodFetcher();
await expect(
fetchWithZod(
z.object({
hello: z.number(),
}),
"https://example.com",
),
).rejects.toMatchInlineSnapshot("[Error: Request failed with status 403]");
});
it("Should handle successes with custom fetchers", async () => {
const fetcher = createZodFetcher(async () => {
return fetch("https://example.com").then((res) => res.json());
});
server.use(
rest.get("https://example.com", (req, res, ctx) => {
return res(ctx.json({ hello: "world" }), ctx.status(200));
}),
);
const response = await fetcher(
z.object({
hello: z.string(),
}),
);
expect(response).toEqual({
hello: "world",
});
});