From 132467ca23db9ff266cb4b7760eff0fd632a2674 Mon Sep 17 00:00:00 2001 From: Max Alcala Date: Wed, 23 Nov 2022 14:37:55 -0300 Subject: [PATCH] tests: discriminatedUnions with optional validators --- .../lib/__tests__/discriminatedUnions.test.ts | 26 +++++++++++++++++++ src/__tests__/discriminatedUnions.test.ts | 26 +++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/deno/lib/__tests__/discriminatedUnions.test.ts b/deno/lib/__tests__/discriminatedUnions.test.ts index cc0f3bd28b..8c98a7b911 100644 --- a/deno/lib/__tests__/discriminatedUnions.test.ts +++ b/deno/lib/__tests__/discriminatedUnions.test.ts @@ -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", [ diff --git a/src/__tests__/discriminatedUnions.test.ts b/src/__tests__/discriminatedUnions.test.ts index dbce353e99..f3aadcc5ae 100644 --- a/src/__tests__/discriminatedUnions.test.ts +++ b/src/__tests__/discriminatedUnions.test.ts @@ -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", [