/
test.ts
58 lines (54 loc) · 1.61 KB
/
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
import test from "ava";
import * as rt from "runtypes";
import { validate } from "./index";
test("basic", (t) => {
const fooSchema = rt.Literal("foo");
t.regex(validate(fooSchema, "bar") as string, /expected.*foo.*bar/i);
t.is(validate(fooSchema, "foo"), undefined);
const recordSchema = rt.Record({
foo: fooSchema,
bar: rt.Number,
baz: rt.Record({
qux: rt.Number.withConstraint((x) => (x <= 0 ? "qux must be > 0" : true)),
mux: rt.Literal("mux"),
}),
});
t.regex(validate(recordSchema, null) as string, /expected.*object.*null/i);
const recordResult1 = validate(recordSchema, {
foo: "BADFOO",
bar: "NOTANUMBER",
baz: { qux: -1, mux: "mux" },
});
t.like(recordResult1, {
foo: "Expected literal `foo`, but was `BADFOO`",
bar: "Expected number, but was string",
baz: {
qux: "Failed constraint check for number: qux must be > 0",
},
});
});
test("useFirstUnionSchemaOnFail", (t) => {
const schema = rt.Union(
rt.Record({ foo: rt.String }),
rt.Record({ bar: rt.Number })
);
const result = validate(
schema,
{ baz: 1 },
{ useFirstUnionSchemaOnFail: true }
);
t.like(result, { foo: "Expected string, but was undefined" });
});
test("useHighestKeyMatchRecordFailure", (t) => {
const schema = rt.Union(
rt.Record({ foo: rt.String }),
rt.Record({ bar: rt.Number })
);
debugger; // eslint-disable-line
const result = validate(
schema,
{ bar: "should_be_a_number_to_pass_but_intentionally_failing" },
{ useHighestKeyMatchRecordFailure: true }
);
t.like(result, { bar: "Expected number, but was string" });
});