@@ -287,4 +287,70 @@ describe('<UseField />', () => {
287287 expect ( formHook ?. getFormData ( ) ) . toEqual ( { name : 'myName' } ) ;
288288 } ) ;
289289 } ) ;
290+
291+ describe ( 'change handlers' , ( ) => {
292+ interface MyForm {
293+ name : string ;
294+ }
295+
296+ const onError = jest . fn ( ) ;
297+ let formHook : FormHook < MyForm > | null = null ;
298+
299+ beforeEach ( ( ) => {
300+ jest . resetAllMocks ( ) ;
301+ formHook = null ;
302+ } ) ;
303+
304+ const onFormHook = ( _form : FormHook < MyForm > ) => {
305+ formHook = _form ;
306+ } ;
307+
308+ const getTestComp = ( fieldConfig : FieldConfig ) => {
309+ const TestComp = ( { onForm } : { onForm : ( form : FormHook ) => void } ) => {
310+ const { form } = useForm < any > ( ) ;
311+
312+ useEffect ( ( ) => {
313+ onForm ( form ) ;
314+ } , [ onForm , form ] ) ;
315+
316+ return (
317+ < Form form = { form } >
318+ < UseField path = "name" config = { fieldConfig } data-test-subj = "myField" onError = { onError } />
319+ </ Form >
320+ ) ;
321+ } ;
322+ return TestComp ;
323+ } ;
324+
325+ const setup = ( fieldConfig : FieldConfig ) => {
326+ return registerTestBed ( getTestComp ( fieldConfig ) , {
327+ memoryRouter : { wrapComponent : false } ,
328+ defaultProps : { onForm : onFormHook } ,
329+ } ) ( ) as TestBed ;
330+ } ;
331+
332+ it ( 'calls onError when validation state changes' , async ( ) => {
333+ const {
334+ form : { setInputValue } ,
335+ } = setup ( {
336+ validations : [
337+ {
338+ validator : ( { value } ) => ( value === '1' ? undefined : { message : 'oops!' } ) ,
339+ } ,
340+ ] ,
341+ } ) ;
342+
343+ expect ( onError ) . toBeCalledTimes ( 0 ) ;
344+ await act ( async ( ) => {
345+ setInputValue ( 'myField' , '0' ) ;
346+ } ) ;
347+ expect ( onError ) . toBeCalledTimes ( 1 ) ;
348+ expect ( onError ) . toBeCalledWith ( [ 'oops!' ] ) ;
349+ await act ( async ( ) => {
350+ setInputValue ( 'myField' , '1' ) ;
351+ } ) ;
352+ expect ( onError ) . toBeCalledTimes ( 2 ) ;
353+ expect ( onError ) . toBeCalledWith ( null ) ;
354+ } ) ;
355+ } ) ;
290356} ) ;
0 commit comments