forked from colinhacks/zod
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpromise.test.ts
More file actions
90 lines (77 loc) · 2.37 KB
/
promise.test.ts
File metadata and controls
90 lines (77 loc) · 2.37 KB
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 { util } from "../helpers/util";
import * as z from "../index";
const promSchema = z.promise(
z.object({
name: z.string(),
age: z.number(),
})
);
test("promise inference", () => {
type promSchemaType = z.infer<typeof promSchema>;
const t1: util.AssertEqual<
promSchemaType,
Promise<{ name: string; age: number }>
> = true;
expect(t1).toBeTruthy();
});
test("promise parsing success", async () => {
const pr = promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 }));
expect(pr).toBeInstanceOf(Promise);
const result = await pr;
expect(typeof result).toBe("object");
expect(typeof result.age).toBe("number");
expect(typeof result.name).toBe("string");
});
test("promise parsing success 2", () => {
const fakePromise = {
then() {
return this;
},
catch() {
return this;
},
};
promSchema.parse(fakePromise);
});
test("promise parsing fail", async () => {
const bad = promSchema.parse(Promise.resolve({ name: "Bobby", age: "10" }));
// return await expect(bad).resolves.toBe({ name: 'Bobby', age: '10' });
return await expect(bad).rejects.toBeInstanceOf(z.ZodError);
// done();
});
test("promise parsing fail 2", async () => {
const failPromise = promSchema.parse(
Promise.resolve({ name: "Bobby", age: "10" })
);
await expect(failPromise).rejects.toBeInstanceOf(z.ZodError);
// done();/z
});
test("promise parsing fail", () => {
const bad = () => promSchema.parse({ then: () => {}, catch: {} });
expect(bad).toThrow();
});
// test('sync promise parsing', () => {
// expect(() => z.promise(z.string()).parse(Promise.resolve('asfd'))).toThrow();
// });
const asyncFunction = z.function(z.tuple([]), promSchema);
test("async function pass", async () => {
const validatedFunction = asyncFunction.implement(async () => {
return { name: "jimmy", age: 14 };
});
await expect(validatedFunction()).resolves.toEqual({
name: "jimmy",
age: 14,
});
});
test("async function fail", async () => {
const validatedFunction = asyncFunction.implement(() => {
return Promise.resolve("asdf" as any);
});
await expect(validatedFunction()).rejects.toBeInstanceOf(z.ZodError);
});
test("async promise parsing", () => {
const res = z.promise(z.number()).parseAsync(Promise.resolve(12));
expect(res).toBeInstanceOf(Promise);
});