forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-schema.test.ts
More file actions
93 lines (85 loc) · 2.44 KB
/
json-schema.test.ts
File metadata and controls
93 lines (85 loc) · 2.44 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
91
92
93
import {expect, test} from 'vitest';
import {assert} from './asserts.ts';
import {jsonObjectSchema, jsonSchema} from './json-schema.ts';
import * as v from './valita.ts';
import {parse} from './valita.ts';
test('json schema', () => {
const t = <T>(s: v.Type<T>, v: unknown, message?: string) => {
let ex;
try {
const parsed = parse(v, s);
expect(parsed).toBe(v);
} catch (err) {
ex = err;
}
if (message !== undefined) {
assert(ex instanceof TypeError);
expect(ex.message).toBe(message);
} else {
expect(ex).toBe(undefined);
}
};
{
t(jsonSchema, 1);
t(jsonSchema, '');
t(jsonSchema, 'hello');
t(jsonSchema, true);
t(jsonSchema, false);
t(jsonSchema, null);
t(jsonSchema, []);
t(jsonSchema, {});
t(jsonSchema, [1, 2, 3]);
t(jsonSchema, {a: 1, b: 2});
t(jsonSchema, {a: 1, b: 2, c: [1, 2, 3]});
}
{
const s = v.object({
a: v.object({
b: jsonSchema,
}),
});
t(s, {a: {b: 1n}}, 'Not a JSON value at a.b. Got 1n');
t(s, {a: {b: {x: {y: 2n}}}}, 'Not a JSON value at a.b.x.y. Got 2n');
t(s, {a: {b: undefined}}, 'Not a JSON value at a.b. Got undefined');
}
});
test('json object schema', () => {
const t = <T>(s: v.Type<T>, v: unknown, message?: string) => {
let ex;
try {
const parsed = parse(v, s);
expect(parsed).toBe(v);
} catch (err) {
ex = err;
}
if (message !== undefined) {
assert(ex instanceof TypeError);
expect(ex.message).toBe(message);
} else {
expect(ex).toBe(undefined);
}
};
{
t(jsonObjectSchema, 1, 'Not a JSON object. Got 1');
t(jsonObjectSchema, '', 'Not a JSON object. Got ""');
t(jsonObjectSchema, 'hello', 'Not a JSON object. Got "hello"');
t(jsonObjectSchema, true, 'Not a JSON object. Got true');
t(jsonObjectSchema, false, 'Not a JSON object. Got false');
t(jsonObjectSchema, null, 'Not a JSON object. Got null');
t(jsonObjectSchema, []);
t(jsonObjectSchema, {});
t(jsonObjectSchema, [1, 2, 3]);
t(jsonObjectSchema, {a: 1, b: 2});
t(jsonObjectSchema, {a: 1, b: 2, c: [1, 2, 3]});
}
{
const s = v.object({
a: v.object({
b: jsonObjectSchema,
}),
});
t(s, {a: {b: 1n}}, 'Not a JSON object at a.b. Got 1n');
t(s, {a: {b: {x: {y: 2n}}}}, 'Not a JSON object at a.b.x.y. Got 2n');
t(s, {a: {b: undefined}}, 'Not a JSON object at a.b. Got undefined');
}
});