@@ -437,7 +437,76 @@ describe('useAJVForm with multiple field updates', () => {
437
437
438
438
expect ( result . current . isDirty ) . toBe ( true ) ;
439
439
} ) ;
440
+ } ) ;
441
+
442
+ describe ( 'useAJVForm should properly set errors programmatically using setErrors function' , ( ) => {
443
+ it ( 'sets the errors using form.setErrors without having any userDefinedMessages' , ( ) => {
444
+ const initialData = { title : '' , description : '' } ;
445
+ const schema : JSONSchemaType < { title : string ; description : string } > = {
446
+ type : 'object' ,
447
+ required : [ 'title' , 'description' ] ,
448
+ properties : {
449
+ title : { type : 'string' } ,
450
+ description : { type : 'string' } ,
451
+ } ,
452
+ } ;
453
+
454
+ const { result } = renderHook ( ( ) => useAJVForm ( initialData , schema ) ) ;
455
+
456
+ result . current . setErrors ( [
457
+ {
458
+ instancePath : '/title' ,
459
+ keyword : 'required' ,
460
+ params : { missingProperty : 'title' } ,
461
+ schemaPath : '#/required' ,
462
+ } ,
463
+ {
464
+ instancePath : '/description' ,
465
+ keyword : 'required' ,
466
+ params : { missingProperty : 'description' } ,
467
+ schemaPath : '#/required' ,
468
+ } ,
469
+ ] ) ;
470
+
471
+ expect ( result . current . state . title . error ) . toBe ( 'title is required.' ) ;
472
+ expect ( result . current . state . description . error ) . toBe ( 'description is required.' ) ;
473
+ } ) ;
474
+
475
+ it ( 'sets the errors using form.setErrors with userDefinedMessages' , ( ) => {
476
+ const initialData = { title : '' , description : '' } ;
477
+ const schema : JSONSchemaType < { title : string ; description : string } > = {
478
+ type : 'object' ,
479
+ required : [ 'title' , 'description' ] ,
480
+ properties : {
481
+ title : { type : 'string' } ,
482
+ description : { type : 'string' } ,
483
+ } ,
484
+ } ;
485
+
486
+ const { result } = renderHook ( ( ) =>
487
+ useAJVForm ( initialData , schema , {
488
+ userDefinedMessages : {
489
+ required : ( ) => 'Monkey message' ,
490
+ } ,
491
+ } ) ,
492
+ ) ;
440
493
441
- // Additional tests can be written to cover other scenarios such as validation,
442
- // resetting the form, handling errors, etc., when multiple fields are involved.
494
+ result . current . setErrors ( [
495
+ {
496
+ instancePath : '/title' ,
497
+ keyword : 'required' ,
498
+ params : { missingProperty : 'title' } ,
499
+ schemaPath : '#/required' ,
500
+ } ,
501
+ {
502
+ instancePath : '/description' ,
503
+ keyword : 'required' ,
504
+ params : { missingProperty : 'description' } ,
505
+ schemaPath : '#/required' ,
506
+ } ,
507
+ ] ) ;
508
+
509
+ expect ( result . current . state . title . error ) . toBe ( 'Monkey message' ) ;
510
+ expect ( result . current . state . description . error ) . toBe ( 'Monkey message' ) ;
511
+ } ) ;
443
512
} ) ;
0 commit comments