forked from rjsf-team/react-jsonschema-form
/
createAjvInstance.test.ts
80 lines (76 loc) · 2.81 KB
/
createAjvInstance.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
import Ajv, { Ajv as AjvType } from 'ajv';
import createAjvInstance, { AJV_CONFIG, COLOR_FORMAT_REGEX, DATA_URL_FORMAT_REGEX } from '../src/createAjvInstance';
import { CustomValidatorOptionsType } from '../src';
jest.mock('ajv');
export const CUSTOM_OPTIONS: CustomValidatorOptionsType = {
additionalMetaSchemas: [
require('ajv/lib/refs/json-schema-draft-04.json'),
],
customFormats: {
'phone-us': /\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{4}$/,
'area-code': /\d{3}/,
},
ajvOptionsOverrides: {
$data: true,
verbose: true,
}
};
describe('createAjvInstance()', () => {
describe('no additional meta schemas or custom formats', () => {
let ajv: AjvType;
beforeAll(() => {
ajv = createAjvInstance();
});
afterAll(() => {
(Ajv as unknown as jest.Mock).mockClear();
});
it('expect a new Ajv to be constructed with the AJV_CONFIG', () => {
expect(Ajv).toHaveBeenCalledWith(AJV_CONFIG);
});
it('addFormat() was called twice', () => {
expect(ajv.addFormat).toHaveBeenCalledTimes(2);
});
it('the first addFormat() was for data-url', () => {
expect(ajv.addFormat).toHaveBeenNthCalledWith(1, 'data-url', DATA_URL_FORMAT_REGEX);
});
it('the second addFormat() was for color', () => {
expect(ajv.addFormat).toHaveBeenNthCalledWith(2, 'color', COLOR_FORMAT_REGEX);
});
it('addMetaSchema was not called', () => {
expect(ajv.addMetaSchema).not.toHaveBeenCalled();
});
});
describe('no additional meta schemas or custom formats', () => {
let ajv: AjvType;
beforeAll(() => {
ajv = createAjvInstance(
CUSTOM_OPTIONS.additionalMetaSchemas,
CUSTOM_OPTIONS.customFormats,
CUSTOM_OPTIONS.ajvOptionsOverrides
);
});
afterAll(() => {
(Ajv as unknown as jest.Mock).mockClear();
});
it('expect a new Ajv to be constructed with the AJV_CONFIG', () => {
expect(Ajv).toHaveBeenCalledWith({ ...AJV_CONFIG, ...CUSTOM_OPTIONS.ajvOptionsOverrides });
});
it('addFormat() was called twice', () => {
expect(ajv.addFormat).toHaveBeenCalledTimes(4);
});
it('the first addFormat() was for data-url', () => {
expect(ajv.addFormat).toHaveBeenNthCalledWith(1, 'data-url', DATA_URL_FORMAT_REGEX);
});
it('the second addFormat() was for color', () => {
expect(ajv.addFormat).toHaveBeenNthCalledWith(2, 'color', COLOR_FORMAT_REGEX);
});
it('the remaining addForma() calls were for custom formats', () => {
Object.keys(CUSTOM_OPTIONS.customFormats!).forEach((key: string, i: number) => {
expect(ajv.addFormat).toHaveBeenNthCalledWith(3 + i, key, CUSTOM_OPTIONS.customFormats![key]);
});
});
it('addMetaSchema was not called', () => {
expect(ajv.addMetaSchema).toHaveBeenCalledWith(CUSTOM_OPTIONS.additionalMetaSchemas);
});
});
});