Hi can anyone explain how to test formik with jest in react native

Viewed 861

Hi I created form builder with formik for react native. I'm using jest for testing, but when I test onSubmit is not calling can anyone please explain how to test.

     function FormBuilder({data, onSubmit, initialValues, navigation}) {
          const formik = useFormik({
            enableReinitialize: true,
            initialValues: initialValues,
            onSubmit: data => {
              onSubmit(data);
            },
          });
    
      return (
        <View>
          {data.map((item,index) => {
            switch (item.type) {
              case 'text':
                return (
                  <TextBox
                  key={index}
                    onChangeText={formik.handleChange(item.name)}
                    onBlur={formik.handleBlur(item.name)}
                    value={formik.values[item.name]}
                    label={item.name}
                    touched={formik.touched}
                    errors={formik.errors}
                    required={
                      !!item.validators &&
                      item.validators.find(valid => valid.type === 'required')
                    }
                    {...item}
                  />
                );
              case 'button':
                return (
                  <CustomButton key={index} testID={item.testID} title= 
             {item.name} onPress={formik.handleSubmit} />
            );
           }
          })}
        </View>
         )
         }

and I call this component like this in my screen. Can anyone explain how can we write test Integration test for this

            <FormBuilder
                  initialValues={initialValues}
                  data={[
                    {
                      type: 'text',
                      name: 'whatsAppNumber',
                      testID: 'input',
                     
                    },
                    {type: 'button', name: 'login', testID: 'button'},
                  ]}
                  onSubmit={submitData}
                />
1 Answers

you can test your code by following method, please use msw for creating dummy server for api call.

import {fireEvent, render,} from '@testing-library/react-native';
describe('Login Screen', () => {
  it('should validate form', async () => {
  
    const {getByTestId} = render(<Login />);
    const numberField = getByTestId('input');
    const button = getByTestId('button');
    expect(numberField).toBeDefined();
    expect(button).toBeDefined();
    fireEvent.changeText(numberField, '9876543215');
    fireEvent.press(button)

    await waitFor(() =>{
     //expect your function to be called
  })
 });
});
Related