/
custom.test.ts
83 lines (69 loc) · 2.07 KB
/
custom.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
import { custom, CustomCallback, CustomSchema, Infer } from '../../src';
import { runInProd } from '../helpers';
import { runCommonTests } from './runCommonTests';
describe('custom()', () => {
let schema: CustomSchema<string>;
const cb: CustomCallback<string> = (value) => {
if (typeof value !== 'string' && value !== null) {
throw new TypeError('Must be a string!!!');
}
};
beforeEach(() => {
schema = custom<string>(cb, 'xyz');
});
const stringCustom = custom(() => 'abc', '');
const arrayCustom = custom(() => [1, 2, 3], [0]);
const tupleCustom = custom<[string, number]>(() => ['a', 1], ['z', 0]);
type StringCustom = Infer<typeof stringCustom>;
type ArrayCustom = Infer<typeof arrayCustom>;
type TupleCustom = Infer<typeof tupleCustom>;
runCommonTests((defaultValue) => custom<string>(cb, defaultValue), 'abc', {
defaultValue: 'xyz',
});
describe('type()', () => {
it('returns "custom"', () => {
expect(custom(cb).type()).toBe('custom');
});
});
describe('validateType()', () => {
it('errors if a non-function is passed during creation', () => {
expect(() => {
// @ts-expect-error Invalid type
custom(123);
}).toThrow('Custom requires a validation function.');
});
it('doesnt error if a string 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('xyz');
});
it('errors if null is passed', () => {
expect(() => {
schema.validate(null);
}).toThrow('Null is not allowed.');
});
it('errors if a non-string is passed', () => {
expect(() => {
// @ts-expect-error Invalid type
schema.validate(123);
}).toThrow('Must be a string!!!');
});
describe('production', () => {
it(
'doesnt error if a non-string is passed',
runInProd(() => {
expect(() => {
// @ts-expect-error Invalid type
schema.validate(123);
}).not.toThrow();
}),
);
});
});
});