diff options
author | Florian Dold <florian.dold@gmail.com> | 2019-12-14 17:55:31 +0100 |
---|---|---|
committer | Florian Dold <florian.dold@gmail.com> | 2019-12-14 17:55:31 +0100 |
commit | 60d154c36bbd6773bbed44da82b17f211604c4b4 (patch) | |
tree | e4be6f7e16a19c7e0e18acc7da6e94161742395e /src/util/codec-test.ts | |
parent | 749b96284ae0a7e6d03034806deab998a36b7cf6 (diff) |
union codecs, error messages
Diffstat (limited to 'src/util/codec-test.ts')
-rw-r--r-- | src/util/codec-test.ts | 47 |
1 files changed, 44 insertions, 3 deletions
diff --git a/src/util/codec-test.ts b/src/util/codec-test.ts index d7edd545f..0d1ab5603 100644 --- a/src/util/codec-test.ts +++ b/src/util/codec-test.ts @@ -19,14 +19,34 @@ */ import test from "ava"; -import { stringCodec, objectCodec } from "./codec"; +import { + stringCodec, + objectCodec, + unionCodec, + Codec, + stringConstCodec, +} from "./codec"; interface MyObj { foo: string; } -test("basic codec", (t) => { - const myObjCodec = objectCodec<MyObj>().property("foo", stringCodec).build("MyObj"); +interface AltOne { + type: "one"; + foo: string; +} + +interface AltTwo { + type: "two"; + bar: string; +} + +type MyUnion = AltOne | AltTwo; + +test("basic codec", t => { + const myObjCodec = objectCodec<MyObj>() + .property("foo", stringCodec) + .build<MyObj>("MyObj"); const res = myObjCodec.decode({ foo: "hello" }); t.assert(res.foo === "hello"); @@ -34,3 +54,24 @@ test("basic codec", (t) => { const res2 = myObjCodec.decode({ foo: 123 }); }); }); + +test("union", t => { + const altOneCodec: Codec<AltOne> = objectCodec<AltOne>() + .property("type", stringConstCodec("one")) + .property("foo", stringCodec) + .build("AltOne"); + const altTwoCodec: Codec<AltTwo> = objectCodec<AltTwo>() + .property("type", stringConstCodec("two")) + .property("bar", stringCodec) + .build("AltTwo"); + const myUnionCodec: Codec<MyUnion> = unionCodec<MyUnion, "type">("type") + .alternative("one", altOneCodec) + .alternative("two", altTwoCodec) + .build<MyUnion>("MyUnion"); + + const res = myUnionCodec.decode({ type: "one", foo: "bla" }); + t.is(res.type, "one"); + if (res.type == "one") { + t.is(res.foo, "bla"); + } +}); |