/
union.test.ts
481 lines (425 loc) · 13.4 KB
/
union.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import {
array,
bool,
custom,
Infer,
instance,
number,
object,
shape,
string,
tuple,
union,
UnionSchema,
} from '../../src';
import { runInProd } from '../helpers';
import { runCommonTests } from './runCommonTests';
class Foo {}
class Bar {}
interface ExampleShape {
foo: string;
bar: number;
baz: boolean;
}
describe('union()', () => {
type UnionStrings = 'bar' | 'baz' | 'foo';
type Union = Foo | Record<string, number> | string[] | UnionStrings | number | true | null;
let schema: UnionSchema<Union>;
beforeEach(() => {
schema = union<Union>('baz').of([
array().of(string()),
bool(true).onlyTrue(),
number().between(0, 5),
instance().of(Foo),
object().of(number()),
string('foo').oneOf(['foo', 'bar', 'baz']),
]);
});
type AllUnion = Infer<typeof schema>;
runCommonTests<Union>(
(defaultValue) =>
union<Union>(defaultValue!).of([
array().of(string()),
bool(true).onlyTrue(),
number().between(0, 5),
instance().of(Foo),
object().of(number()),
string('foo').oneOf(['foo', 'bar', 'baz']),
]),
'baz',
{
defaultValue: 1,
},
);
it('errors if a unsupported type is used', () => {
expect(() => {
union<boolean | number | string>(0)
.of([bool(), number(), string()])
// @ts-expect-error Invalid type
.validate({});
}).toThrowErrorMatchingInlineSnapshot(`"Value must be one of: boolean, number, string."`);
});
it('errors if a nested union is used', () => {
expect(() => {
union<string[]>([])
.of([string('foo'), union([]).of([number(), bool()])])
.validate([]);
}).toThrowErrorMatchingInlineSnapshot(`"Nested unions are not supported."`);
});
it('errors with the class name for instance checks', () => {
expect(() => {
union<Buffer | number | null>(0)
.of([number(), instance().of(Buffer)])
// @ts-expect-error Invalid type
.validate(new Foo());
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: number, Buffer. Received class with the following invalidations:
- Must be an instance of \\"Buffer\\"."
`);
});
it('returns default value if value is undefined', () => {
expect(schema.validate(undefined)).toEqual('baz');
});
it('runs array check', () => {
expect(() => {
schema.validate([123]);
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received array/tuple with the following invalidations:
- Invalid field \\"[0]\\". Must be a string."
`);
});
it('runs boolean check', () => {
expect(() => {
schema.validate(false);
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received boolean with the following invalidations:
- May only be \`true\`."
`);
});
it('runs custom check', () => {
expect(() => {
union(0)
.of([
string(),
custom((value) => {
if (typeof value === 'number') {
throw new TypeError('Encountered a number!');
}
}, ''),
])
.validate(123);
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: string, custom. Received number with the following invalidations:
- Encountered a number!"
`);
});
it('runs instance check', () => {
expect(() => {
schema.validate(new Bar());
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received class with the following invalidations:
- Must be an instance of \\"Foo\\"."
`);
});
it('runs number check', () => {
expect(() => {
schema.validate(10);
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received number with the following invalidations:
- Number must be between 0 and 5."
`);
});
it('runs object check', () => {
expect(() => {
schema.validate({ foo: 'foo' });
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received object/shape with the following invalidations:
- Invalid field \\"foo\\". Must be a number."
`);
});
it('runs shape check', () => {
expect(() => {
union({ foo: '', bar: 0 })
.of([
shape({
foo: string(),
bar: number(),
}),
])
// @ts-expect-error Invalid type
.validate({ foo: 123 });
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: shape<{ foo: string, bar: number }>. Received object/shape with the following invalidations:
- Invalid field \\"foo\\". Must be a string."
`);
});
it('runs string check', () => {
expect(() => {
schema.validate('qux');
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received string with the following invalidations:
- String must be one of: foo, bar, baz"
`);
});
it('runs tuple check', () => {
expect(() => {
union(['foo', 'bar', 'baz'])
.of([tuple<['foo', 'bar', 'baz']>([string(), string(), string()])])
// @ts-expect-error Invalid type
.validate([1]);
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: tuple<string, string, string>. Received array/tuple with the following invalidations:
- Invalid field \\"[0]\\". Must be a string."
`);
});
it('runs correctly for valid values', () => {
expect(schema.validate('foo')).toBe('foo');
expect(schema.validate(3)).toBe(3);
expect(schema.validate(true)).toBe(true);
});
it('supports multiple array schemas', () => {
const arrayUnion = union<number[] | string[]>([]).of([
array().of(string()),
array().of(number()),
]);
expect(() => {
// @ts-expect-error Invalid type
arrayUnion.validate([true]);
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, array<number>. Received array/tuple with the following invalidations:
- Invalid field \\"[0]\\". Must be a string.
- Invalid field \\"[0]\\". Must be a number."
`);
expect(() => {
arrayUnion.validate([123]);
}).not.toThrow();
expect(() => {
arrayUnion.validate(['abc']);
}).not.toThrow();
});
it('supports multiple object schemas', () => {
const objectUnion = union<Record<string, number | string>>({}).of([
object().of(string()),
object().of(number()),
]);
expect(() => {
// @ts-expect-error Invalid type
objectUnion.validate({ foo: true });
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: object<string>, object<number>. Received object/shape with the following invalidations:
- Invalid field \\"foo\\". Must be a string.
- Invalid field \\"foo\\". Must be a number."
`);
expect(() => {
objectUnion.validate({ foo: 123 });
}).not.toThrow();
expect(() => {
objectUnion.validate({ foo: 'abc' });
}).not.toThrow();
});
it('supports arrays and tuples correctly', () => {
const mixedUnion = union<[string, number][] | string[]>([]).of([
array().of(string()),
array().of(tuple<[string, number]>([string(), number()])),
]);
expect(mixedUnion.validate(['a', 'b', 'c'])).toEqual(['a', 'b', 'c']);
expect(
mixedUnion.validate([
['a', 1],
['b', 2],
]),
).toEqual([
['a', 1],
['b', 2],
]);
});
it('supports very complex nested unions', () => {
const options = union({}).of([bool(), object()]);
const complexUnion = union({}).of([
// 'foo'
// ['foo', true]
// ['foo', {}]
array().of(
union('').of([
string().notEmpty(),
tuple<[string, boolean | object]>([string().notEmpty(), options]),
]),
),
// foo: true
// foo: {}
object().of(options).notNullable(),
]);
// array only
expect(() => complexUnion.validate([])).not.toThrow();
expect(() => complexUnion.validate(['a', 'b', 'c'])).not.toThrow();
// tuple only
expect(() =>
complexUnion.validate([
['a', true],
['b', false],
['c', {}],
]),
).not.toThrow();
// arrays and tuples
expect(() => complexUnion.validate(['a', ['b', false], ['c', {}], 'd'])).not.toThrow();
// object only
expect(() => complexUnion.validate({})).not.toThrow();
expect(() => complexUnion.validate({ a: true, b: false, c: {} })).not.toThrow();
// invalid
expect(() => complexUnion.validate(['a', ['b', null], ['c', {}], 'd', 123]))
.toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string | tuple<string, boolean | object>>, object<boolean | object>. Received array/tuple with the following invalidations:
- Invalid field \\"[1]\\". Value must be one of: string, tuple<string, boolean | object>. Received array/tuple with the following invalidations:
- Invalid field \\"[1][1]\\". Null is not allowed."
`);
expect(() => complexUnion.validate({ a: true, b: 123, c: {} }))
.toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string | tuple<string, boolean | object>>, object<boolean | object>. Received object/shape with the following invalidations:
- Invalid field \\"b\\". Value must be one of: boolean, object."
`);
});
it('supports object and shape schemas in parallel', () => {
const mixedUnion = union<ExampleShape | Record<string, string>>({}).of([
shape({
foo: string(),
bar: number(),
baz: bool(),
}).exact(),
object().of(string()),
]);
expect(() => {
// @ts-expect-error Invalid type
mixedUnion.validate({ unknown: true });
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: shape<{ foo: string, bar: number, baz: boolean }>, object<string>. Received object/shape with the following invalidations:
- Unknown fields: unknown.
- Invalid field \\"unknown\\". Must be a string."
`);
expect(() => {
// @ts-expect-error Invalid type
mixedUnion.validate({ foo: 123 });
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: shape<{ foo: string, bar: number, baz: boolean }>, object<string>. Received object/shape with the following invalidations:
- Invalid field \\"foo\\". Must be a string."
`);
expect(() => {
// @ts-expect-error Invalid type
mixedUnion.validate({ foo: 'abc', bar: 'abc', baz: 123 });
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: shape<{ foo: string, bar: number, baz: boolean }>, object<string>. Received object/shape with the following invalidations:
- Invalid field \\"bar\\". Must be a number.
- Invalid field \\"baz\\". Must be a string."
`);
expect(() => {
// @ts-expect-error Invalid type
mixedUnion.validate({ foo: 'abc', bar: 123 });
}).not.toThrow();
expect(() => {
mixedUnion.validate({ key: 'value' });
}).not.toThrow();
});
it('returns shapes as their full objects', () => {
const shapesUnion = union<ExampleShape | Record<string, number>>({}).of([
shape({
foo: string().required(),
bar: number(),
baz: bool(),
}).exact(),
object().of(number()),
]);
expect(shapesUnion.validate({})).toEqual({});
// @ts-expect-error Mixed types
expect(shapesUnion.validate({ foo: 'foo' })).toEqual({
foo: 'foo',
bar: 0,
baz: false,
});
expect(shapesUnion.validate({ a: 1, b: 2 })).toEqual({ a: 1, b: 2 });
});
it('returns an array of shapes as their full objects', () => {
const arrayShapesUnion = union<ExampleShape[]>([]).of([
array().of(
shape({
foo: string(),
bar: number(),
baz: bool(),
}).exact(),
),
]);
expect(arrayShapesUnion.validate([])).toEqual([]);
// @ts-expect-error Partial types are allowed?
expect(arrayShapesUnion.validate([{ foo: 'foo' }, { bar: 123 }, { baz: true }])).toEqual([
{
foo: 'foo',
bar: 0,
baz: false,
},
{
foo: '',
bar: 123,
baz: false,
},
{
foo: '',
bar: 0,
baz: true,
},
]);
});
describe('of()', () => {
it('errors if a non-array is passed', () => {
expect(() => {
// @ts-expect-error Invalid type
union('').of(123);
}).toThrow('A non-empty array of schemas are required for a union.');
});
it('errors if an empty array is passed', () => {
expect(() => {
union('').of([]);
}).toThrow('A non-empty array of schemas are required for a union.');
});
});
describe('type()', () => {
it('returns list of types', () => {
expect(schema.type()).toBe(
'array<string> | boolean | number | Foo | object<number> | string',
);
});
});
describe('validateType()', () => {
it('errors if an invalid value is passed', () => {
expect(() => {
schema.validate('not a whitelisted string');
}).toThrowErrorMatchingInlineSnapshot(`
"Value must be one of: array<string>, boolean, number, Foo, object<number>, string. Received string with the following invalidations:
- String must be one of: foo, bar, baz"
`);
});
it('doesnt error if a valid value is passed', () => {
expect(() => {
schema.validate('foo');
}).not.toThrow();
});
it('returns passed string', () => {
expect(schema.validate('foo')).toBe('foo');
});
it('returns default value if undefined passed', () => {
expect(schema.validate(undefined)).toBe('baz');
});
it('errors if null is passed', () => {
expect(() => {
schema.validate(null);
}).toThrow('Null is not allowed.');
});
describe('production', () => {
it(
'doesnt error if a non-string is passed',
runInProd(() => {
expect(() => {
schema.validate('invalid string');
}).not.toThrow();
}),
);
});
});
});