Debian Codegraph @

packages/validator-ajv6/test/validator.test.ts

raw symbols SCIP
1 import {
2 ErrorSchema,
3 ErrorSchemaBuilder,
4 FormValidation,
5 RJSFSchema,
6 RJSFValidationError,
7 UiSchema,
8 ValidatorType,
9 } from '@rjsf/utils';
10
11 import AJV6Validator from '../src/validator';
12
13 const illFormedKey = "bar.`'[]()=+*&^%$#@!";
14 const metaSchemaDraft4 = require('ajv/lib/refs/json-schema-draft-04.json');
15 const metaSchemaDraft6 = require('ajv/lib/refs/json-schema-draft-06.json');
16
17 describe('AJV6Validator', () => {
18 let builder: ErrorSchemaBuilder;
19 beforeAll(() => {
20 builder = new ErrorSchemaBuilder();
21 });
22 afterEach(() => {
23 builder.resetAllErrors();
24 });
25 describe('default options', () => {
26 // Use the AJV6Validator to access the `withIdRefPrefix` function
27 let validator: AJV6Validator;
28 beforeAll(() => {
29 validator = new AJV6Validator({});
30 });
31 describe('validator.isValid()', () => {
32 it('should return true if the data is valid against the schema', () => {
33 const schema: RJSFSchema = {
34 type: 'object',
35 properties: {
36 foo: { type: 'string' },
37 },
38 };
39
40 expect(validator.isValid(schema, { foo: 'bar' }, schema)).toBe(true);
41 });
42 it('should return false if the data is not valid against the schema', () => {
43 const schema: RJSFSchema = {
44 type: 'object',
45 properties: {
46 foo: { type: 'string' },
47 },
48 };
49
50 expect(validator.isValid(schema, { foo: 12345 }, schema)).toBe(false);
51 });
52 it('should return false if the schema is invalid', () => {
53 const schema: RJSFSchema = 'foobarbaz' as unknown as RJSFSchema;
54
55 expect(validator.isValid(schema, { foo: 'bar' }, schema)).toBe(false);
56 });
57 it('should return true if the data is valid against the schema including refs to rootSchema', () => {
58 const schema: RJSFSchema = {
59 anyOf: [{ $ref: '#/definitions/foo' }],
60 };
61 const rootSchema: RJSFSchema = {
62 definitions: {
63 foo: {
64 properties: {
65 name: { type: 'string' },
66 },
67 },
68 },
69 };
70 const formData = {
71 name: 'John Doe',
72 };
73
74 expect(validator.isValid(schema, formData, rootSchema)).toBe(true);
75 });
76 });
77 describe('validator.toErrorList()', () => {
78 it('should return empty list for unspecified errorSchema', () => {
79 expect(validator.toErrorList()).toEqual([]);
80 });
81 it('should convert an errorSchema into a flat list', () => {
82 const errorSchema = builder
83 .addErrors(['err1', 'err2'])
84 .addErrors(['err3', 'err4'], 'a.b')
85 .addErrors(['err5'], 'c').ErrorSchema;
86 expect(validator.toErrorList(errorSchema)).toEqual([
87 { property: '.', message: 'err1', stack: '. err1' },
88 { property: '.', message: 'err2', stack: '. err2' },
89 { property: '.a.b', message: 'err3', stack: '.a.b err3' },
90 { property: '.a.b', message: 'err4', stack: '.a.b err4' },
91 { property: '.c', message: 'err5', stack: '.c err5' },
92 ]);
93 });
94 });
95 describe('validator.validateFormData()', () => {
96 describe('No custom validate function, single value', () => {
97 let errors: RJSFValidationError[];
98 let errorSchema: ErrorSchema;
99
100 beforeAll(() => {
101 const schema: RJSFSchema = {
102 type: 'object',
103 properties: {
104 foo: { type: 'string' },
105 [illFormedKey]: { type: 'string' },
106 },
107 };
108 const result = validator.validateFormData({ foo: 42, [illFormedKey]: 41 }, schema);
109 errors = result.errors;
110 errorSchema = result.errorSchema;
111 });
112
113 it('should return an error list', () => {
114 expect(errors).toHaveLength(2);
115 expect(errors[0].message).toEqual('should be string');
116 expect(errors[1].message).toEqual('should be string');
117 });
118 it('should return an errorSchema', () => {
119 expect(errorSchema.foo!.__errors).toHaveLength(1);
120 expect(errorSchema.foo!.__errors![0]).toEqual('should be string');
121 expect(errorSchema[illFormedKey]!.__errors).toHaveLength(1);
122 expect(errorSchema[illFormedKey]!.__errors![0]).toEqual('should be string');
123 });
124 });
125 describe('Validating multipleOf with a float', () => {
126 let errors: RJSFValidationError[];
127 beforeAll(() => {
128 const schema: RJSFSchema = {
129 type: 'object',
130 properties: {
131 price: {
132 title: 'Price per task ($)',
133 type: 'number',
134 multipleOf: 0.01,
135 minimum: 0,
136 },
137 },
138 };
139 const result = validator.validateFormData({ price: 0.14 }, schema);
140 errors = result.errors;
141 });
142 it('should not return an error', () => {
143 expect(errors).toHaveLength(0);
144 });
145 });
146 describe('Validating multipleOf with a float, with multiple errors', () => {
147 let errors: RJSFValidationError[];
148 let errorSchema: ErrorSchema;
149 beforeAll(() => {
150 const schema: RJSFSchema = {
151 type: 'object',
152 properties: {
153 price: {
154 title: 'Price per task ($)',
155 type: 'number',
156 multipleOf: 0.03,
157 minimum: 1,
158 },
159 },
160 };
161 const result = validator.validateFormData({ price: 0.14 }, schema);
162 errors = result.errors;
163 errorSchema = result.errorSchema;
164 });
165 it('should have 2 errors', () => {
166 expect(errors).toHaveLength(2);
167 });
168 it('first error is for minimum', () => {
169 expect(errors[0].message).toEqual('should be >= 1');
170 });
171 it('first error is for multipleOf', () => {
172 expect(errors[1].message).toEqual('should be multiple of 0.03');
173 });
174 it('should return an errorSchema', () => {
175 expect(errorSchema.price!.__errors).toHaveLength(2);
176 expect(errorSchema.price!.__errors).toEqual(['should be >= 1', 'should be multiple of 0.03']);
177 });
178 });
179 describe('Validating required fields', () => {
180 let errors: RJSFValidationError[];
181 let errorSchema: ErrorSchema;
182 describe('formData is not provided at top level', () => {
183 beforeAll(() => {
184 const schema: RJSFSchema = {
185 type: 'object',
186 required: ['pass1', 'pass2'],
187 properties: {
188 pass1: { type: 'string' },
189 pass2: { type: 'string' },
190 },
191 };
192
193 const formData = { pass1: 'a' };
194 const result = validator.validateFormData(formData, schema);
195 errors = result.errors;
196 errorSchema = result.errorSchema;
197 });
198 it('should return an error list', () => {
199 expect(errors).toHaveLength(1);
200 expect(errors[0].stack).toEqual('.pass2 is a required property');
201 });
202 it('should return an errorSchema', () => {
203 expect(errorSchema.pass2!.__errors).toHaveLength(1);
204 expect(errorSchema.pass2!.__errors![0]).toEqual('is a required property');
205 });
206 });
207 describe('formData is not provided for nested child', () => {
208 beforeAll(() => {
209 const schema: RJSFSchema = {
210 type: 'object',
211 properties: {
212 nested: {
213 type: 'object',
214 required: ['pass1', 'pass2'],
215 properties: {
216 pass1: { type: 'string' },
217 pass2: { type: 'string' },
218 },
219 },
220 },
221 };
222
223 const formData = { nested: { pass1: 'a' } };
224 const result = validator.validateFormData(formData, schema);
225 errors = result.errors;
226 errorSchema = result.errorSchema;
227 });
228 it('should return an error list', () => {
229 expect(errors).toHaveLength(1);
230 expect(errors[0].stack).toEqual('.nested.pass2 is a required property');
231 });
232 it('should return an errorSchema', () => {
233 expect(errorSchema.nested!.pass2!.__errors).toHaveLength(1);
234 expect(errorSchema.nested!.pass2!.__errors![0]).toEqual('is a required property');
235 });
236 });
237 });
238 describe('No custom validate function, single additionalProperties value', () => {
239 let errors: RJSFValidationError[];
240 let errorSchema: ErrorSchema;
241
242 beforeAll(() => {
243 const schema: RJSFSchema = {
244 type: 'object',
245 additionalProperties: {
246 type: 'string',
247 },
248 };
249 const result = validator.validateFormData({ foo: 42 }, schema);
250 errors = result.errors;
251 errorSchema = result.errorSchema;
252 });
253
254 it('should return an error list', () => {
255 expect(errors).toHaveLength(1);
256 expect(errors[0].message).toEqual('should be string');
257 });
258 it('should return an errorSchema', () => {
259 expect(errorSchema.foo!.__errors).toHaveLength(1);
260 expect(errorSchema.foo!.__errors![0]).toEqual('should be string');
261 });
262 });
263 describe('TransformErrors', () => {
264 let errors: RJSFValidationError[];
265 let newErrorMessage: string;
266 let transformErrors: jest.Mock;
267 let uiSchema: UiSchema;
268 beforeAll(() => {
269 const schema: RJSFSchema = {
270 type: 'object',
271 properties: {
272 foo: { type: 'string' },
273 [illFormedKey]: { type: 'string' },
274 },
275 };
276 uiSchema = {
277 foo: { 'ui:label': false },
278 };
279 newErrorMessage = 'Better error message';
280 transformErrors = jest.fn((errors: RJSFValidationError[]) => {
281 return [Object.assign({}, errors[0], { message: newErrorMessage })];
282 });
283 const result = validator.validateFormData(
284 { foo: 42, [illFormedKey]: 41 },
285 schema,
286 undefined,
287 transformErrors,
288 uiSchema
289 );
290 errors = result.errors;
291 });
292
293 it('should use transformErrors function', () => {
294 expect(errors).not.toHaveLength(0);
295 expect(errors[0].message).toEqual(newErrorMessage);
296 });
297 it('transformErrors function was called with uiSchema', () => {
298 expect(transformErrors).toHaveBeenCalledWith(expect.any(Array), uiSchema);
299 });
300 });
301 describe('Custom validate function', () => {
302 let errors: RJSFValidationError[];
303 let errorSchema: ErrorSchema;
304 let validate: jest.Mock;
305 let uiSchema: UiSchema;
306 beforeAll(() => {
307 uiSchema = {
308 foo: { 'ui:label': false },
309 };
310
311 validate = jest.fn((formData: any, errors: FormValidation<any>) => {
312 if (formData.pass1 !== formData.pass2) {
313 errors.pass2!.addError('passwords don`t match.');
314 }
315 return errors;
316 });
317 });
318 describe('formData is provided', () => {
319 beforeAll(() => {
320 const schema: RJSFSchema = {
321 type: 'object',
322 required: ['pass1', 'pass2'],
323 properties: {
324 pass1: { type: 'string' },
325 pass2: { type: 'string' },
326 foo: { type: 'array', items: { type: 'string' } }, // Adding an array for test coverage
327 },
328 };
329 const formData = { pass1: 'a', pass2: 'b', foo: ['a'] };
330 const result = validator.validateFormData(formData, schema, validate, undefined, uiSchema);
331 errors = result.errors;
332 errorSchema = result.errorSchema;
333 });
334 it('should return an error list', () => {
335 expect(errors).toHaveLength(1);
336 expect(errors[0].stack).toEqual('.pass2 passwords don`t match.');
337 });
338 it('should return an errorSchema', () => {
339 expect(errorSchema.pass2!.__errors).toHaveLength(1);
340 expect(errorSchema.pass2!.__errors![0]).toEqual('passwords don`t match.');
341 });
342 it('validate function was called with uiSchema', () => {
343 expect(validate).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), uiSchema);
344 });
345 });
346 describe('formData is missing data', () => {
347 beforeAll(() => {
348 const schema: RJSFSchema = {
349 type: 'object',
350 properties: {
351 pass1: { type: 'string' },
352 pass2: { type: 'string' },
353 },
354 };
355 const formData = { pass1: 'a' };
356 const result = validator.validateFormData(formData, schema, validate);
357 errors = result.errors;
358 errorSchema = result.errorSchema;
359 });
360 it('should return an error list', () => {
361 expect(errors).toHaveLength(1);
362 expect(errors[0].stack).toEqual('.pass2 passwords don`t match.');
363 });
364 it('should return an errorSchema', () => {
365 expect(errorSchema.pass2!.__errors).toHaveLength(1);
366 expect(errorSchema.pass2!.__errors![0]).toEqual('passwords don`t match.');
367 });
368 it('validate function was called with undefined uiSchema', () => {
369 expect(validate).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), undefined);
370 });
371 });
372 });
373 describe('Data-Url validation', () => {
374 let schema: RJSFSchema;
375 beforeAll(() => {
376 schema = {
377 type: 'object',
378 properties: {
379 dataUrlWithName: { type: 'string', format: 'data-url' },
380 dataUrlWithoutName: { type: 'string', format: 'data-url' },
381 },
382 };
383 });
384 it('Data-Url with name is accepted', () => {
385 const formData = {
386 dataUrlWithName: 'data:text/plain;name=file1.txt;base64,x=',
387 };
388 const result = validator.validateFormData(formData, schema);
389 expect(result.errors).toHaveLength(0);
390 });
391 it('Data-Url without name is accepted', () => {
392 const formData = {
393 dataUrlWithoutName: 'data:text/plain;base64,x=',
394 };
395 const result = validator.validateFormData(formData, schema);
396 expect(result.errors).toHaveLength(0);
397 });
398 });
399 describe('Invalid schema', () => {
400 let errors: RJSFValidationError[];
401 let errorSchema: ErrorSchema;
402
403 beforeAll(() => {
404 const schema: RJSFSchema = {
405 type: 'object',
406 properties: {
407 foo: {
408 type: 'string',
409 required: 'invalid_type_non_array' as unknown as string[],
410 },
411 },
412 };
413 const result = validator.validateFormData({ foo: 42 }, schema);
414 errors = result.errors;
415 errorSchema = result.errorSchema;
416 });
417 it('should return an error list', () => {
418 expect(errors).toHaveLength(1);
419 expect(errors[0].name).toEqual('type');
420 expect(errors[0].property).toEqual(".properties['foo'].required");
421 // TODO: This schema path is wrong due to a bug in ajv; change this test when https://github.com/ajv-validator/ajv/issues/512 is fixed.
422 expect(errors[0].schemaPath).toEqual('#/definitions/stringArray/type');
423 expect(errors[0].message).toEqual('should be array');
424 });
425 it('should return an errorSchema', () => {
426 expect(errorSchema.properties!.foo!.required!.__errors).toHaveLength(1);
427 expect(errorSchema.properties!.foo!.required!.__errors![0]).toEqual('should be array');
428 });
429 });
430 });
431 });
432 describe('validator.validateFormData(), custom options', () => {
433 let validator: AJV6Validator;
434 let schema: RJSFSchema;
435 beforeAll(() => {
436 validator = new AJV6Validator({});
437 schema = {
438 $ref: '#/definitions/Dataset',
439 $schema: 'http://json-schema.org/draft-04/schema#',
440 definitions: {
441 Dataset: {
442 properties: {
443 datasetId: {
444 pattern: '\\d+',
445 type: 'string',
446 },
447 },
448 required: ['datasetId'],
449 type: 'object',
450 },
451 },
452 };
453 });
454 it('should return a validation error about meta schema when meta schema is not defined', () => {
455 const errors = validator.validateFormData({ datasetId: 'some kind of text' }, schema);
456 const errMessage = 'no schema with key or ref "http://json-schema.org/draft-04/schema#"';
457 expect(errors.errors).toEqual([{ stack: errMessage }]);
458 expect(errors.errorSchema).toEqual({
459 $schema: { __errors: [errMessage] },
460 });
461 });
462 describe('validating using single custom meta schema', () => {
463 let errors: RJSFValidationError[];
464 beforeAll(() => {
465 validator = new AJV6Validator({
466 additionalMetaSchemas: [metaSchemaDraft4],
467 });
468 const result = validator.validateFormData({ datasetId: 'some kind of text' }, schema);
469 errors = result.errors;
470 });
471 it('should return 1 error about formData', () => {
472 expect(errors).toHaveLength(1);
473 });
474 it('has a pattern match validation error about formData', () => {
475 expect(errors[0].stack).toEqual('.datasetId should match pattern "\\d+"');
476 });
477 });
478 describe('validating using several custom meta schemas', () => {
479 let errors: RJSFValidationError[];
480
481 beforeAll(() => {
482 validator = new AJV6Validator({
483 additionalMetaSchemas: [metaSchemaDraft4, metaSchemaDraft6],
484 });
485 const result = validator.validateFormData({ datasetId: 'some kind of text' }, schema);
486 errors = result.errors;
487 });
488 it('should return 1 error about formData', () => {
489 expect(errors).toHaveLength(1);
490 });
491 it('has a pattern match validation error about formData', () => {
492 expect(errors[0].stack).toEqual('.datasetId should match pattern "\\d+"');
493 });
494 });
495 describe('validating using custom string formats', () => {
496 let validator: ValidatorType;
497 let schema: RJSFSchema;
498 beforeAll(() => {
499 validator = new AJV6Validator({});
500 schema = {
501 type: 'object',
502 properties: {
503 phone: {
504 type: 'string',
505 format: 'phone-us',
506 },
507 },
508 };
509 });
510 it('should not return a validation error if unknown string format is used', () => {
511 const result = validator.validateFormData({ phone: '800.555.2368' }, schema);
512 expect(result.errors.length).toEqual(0);
513 });
514 describe('validating using a custom formats', () => {
515 let errors: RJSFValidationError[];
516
517 beforeAll(() => {
518 validator = new AJV6Validator({
519 customFormats: {
520 'phone-us': /\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{4}$/,
521 'area-code': /\d{3}/,
522 },
523 });
524 const result = validator.validateFormData({ phone: '800.555.2368' }, schema);
525 errors = result.errors;
526 });
527 it('should return 1 error about formData', () => {
528 expect(errors).toHaveLength(1);
529 });
530 it('should return a validation error about formData', () => {
531 expect(errors[0].stack).toEqual('.phone should match format "phone-us"');
532 });
533 describe('prop updates with new custom formats are accepted', () => {
534 beforeAll(() => {
535 const result = validator.validateFormData(
536 { phone: 'abc' },
537 {
538 type: 'object',
539 properties: {
540 phone: {
541 type: 'string',
542 format: 'area-code',
543 },
544 },
545 }
546 );
547 errors = result.errors;
548 });
549
550 it('should return 1 error about formData', () => {
551 expect(errors).toHaveLength(1);
552 });
553 it('should return a validation error about formData', () => {
554 expect(errors[0].stack).toEqual('.phone should match format "area-code"');
555 });
556 });
557 });
558 });
559 });
560 });