@@ -78,41 +78,57 @@ describe("Test validate", () => {
7878} ) ;
7979
8080describe ( "Test add" , ( ) => {
81+ let check ;
8182
82- const v = new Validator ( ) ;
83- const validFn = jest . fn ( ( ) => true ) ;
83+ const v = new Validator ( {
84+ messages : {
85+ // Register our new error message text
86+ evenNumber : "The '{field}' field must be an even number! Actual: {actual}"
87+ }
88+ } ) ;
89+
90+ const validFn = jest . fn ( function ( { schema, messages } , path , context ) {
91+ return {
92+ source : `
93+ if (value % 2 != 0)
94+ ${ this . makeError ( { type : "evenNumber" , actual : "value" , messages } ) }
95+
96+ return value;
97+ `
98+ } ;
99+ } ) ;
84100
85101 it ( "should not contain the new validator" , ( ) => {
86- expect ( v . rules . myValidator ) . toBeUndefined ( ) ;
102+ expect ( v . rules . even ) . toBeUndefined ( ) ;
87103 } ) ;
88104
89105 it ( "should contain the new validator" , ( ) => {
90- v . add ( "myValidator " , validFn ) ;
91- expect ( v . rules . myValidator ) . toBeDefined ( ) ;
106+ v . add ( "even " , validFn ) ;
107+ expect ( v . rules . even ) . toBeDefined ( ) ;
92108 } ) ;
93109
94110 it ( "should call the new validator" , ( ) => {
95111 const schema = {
96- a : { type : "myValidator " }
112+ a : { type : "even " }
97113 } ;
98114
99- const obj = { a : 5 } ;
100-
101- v . validate ( obj , schema ) ;
115+ check = v . compile ( schema ) ;
102116
103117 const context = {
104118 customs : { } ,
105119 rules : expect . any ( Array ) ,
106120 fn : expect . any ( Array ) ,
107- index : 2 ,
108- data : { a : 5 }
121+ index : 2
109122 } ;
110123
111124 expect ( validFn ) . toHaveBeenCalledTimes ( 1 ) ;
112125 expect ( validFn ) . toHaveBeenCalledWith ( expect . any ( Object ) , "a" , context ) ;
113126 } ) ;
114127
115- // TODO: add a real example
128+ it ( "should check the new rule" , ( ) => {
129+ expect ( check ( { a : 5 } ) ) . toEqual ( [ { "type" : "evenNumber" , "field" : "a" , "actual" : 5 , "message" : "The 'a' field must be an even number! Actual: 5" } ] ) ;
130+ expect ( check ( { a : 6 } ) ) . toEqual ( true ) ;
131+ } ) ;
116132
117133} ) ;
118134
0 commit comments