Skip to content

Commit

Permalink
tests: discriminatedUnions with optional validators
Browse files Browse the repository at this point in the history
  • Loading branch information
maxArturo committed Nov 23, 2022
1 parent 60f85fe commit 132467c
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
26 changes: 26 additions & 0 deletions deno/lib/__tests__/discriminatedUnions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,32 @@ test("valid - discriminator value of various primitive types", () => {
});
});

test("valid - wrapped optional discriminator value ", () => {
const schema = z.discriminatedUnion("type", [
z.object({ type: z.literal("1").optional(), val: z.literal(1) }),
z.object({ type: z.literal(1), val: z.literal(2) }),
]);

expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 });
expect(schema.parse({ type: undefined, val: 1 })).toEqual({
type: undefined,
val: 1,
});
expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 });
});

test("valid - collision with multiple undefined discriminators", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("1").optional(), val: z.literal(1) }),
z.object({ type: z.literal(undefined), val: z.literal(2) }),
]);
throw new Error();
} catch (e: any) {
expect(e.message.includes("has duplicate value")).toEqual(true);
}
});

test("invalid - null", () => {
try {
z.discriminatedUnion("type", [
Expand Down
26 changes: 26 additions & 0 deletions src/__tests__/discriminatedUnions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,32 @@ test("valid - discriminator value of various primitive types", () => {
});
});

test("valid - wrapped optional discriminator value ", () => {
const schema = z.discriminatedUnion("type", [
z.object({ type: z.literal("1").optional(), val: z.literal(1) }),
z.object({ type: z.literal(1), val: z.literal(2) }),
]);

expect(schema.parse({ type: "1", val: 1 })).toEqual({ type: "1", val: 1 });
expect(schema.parse({ type: undefined, val: 1 })).toEqual({
type: undefined,
val: 1,
});
expect(schema.parse({ type: 1, val: 2 })).toEqual({ type: 1, val: 2 });
});

test("valid - collision with multiple undefined discriminators", () => {
try {
z.discriminatedUnion("type", [
z.object({ type: z.literal("1").optional(), val: z.literal(1) }),
z.object({ type: z.literal(undefined), val: z.literal(2) }),
]);
throw new Error();
} catch (e: any) {
expect(e.message.includes("has duplicate value")).toEqual(true);
}
});

test("invalid - null", () => {
try {
z.discriminatedUnion("type", [
Expand Down

0 comments on commit 132467c

Please sign in to comment.