jdkschang
jdkschang

Reputation: 65

Mocking onSubmit on react-final-form using react-testing-library

I have a form built using react-final-form, yup, and Material-ui. I am testing using Jest, and @testing-library/react.

TL;DR:


The mocked onSubmit function was not called because I leveraged RFF's validate function. It seems the validate function is hanging during the submit process. Besides mocking the validate function, is there a best practice in building the validator function so the tests recognize that the mocked onSubmit has been called?

When I try to test whether the form has been submitted it seems to hang on the validate method.

fireEvent.submit(getByTestId('test-form')) // or
fireEvent.click(getByTestId('submit-button'))

mocking function failure

The mocked onSubmit function is not recognized and seems to hang on the validate method.

const schema = yup.object().shape({
    code: yup
        .string()
        .trim()
        .required('Please provide a Code')
        .max(32, 'The Code is too long')
})

const validate = values =>
    schema
        .validate(values, { abortEarly: false })
        .then(valid => ({}))
        .catch(err => extractError(err))

<Form
  onSubmit={onSubmit}
  validate={validate}
  render={({ handleSubmit }) => (
    <form onSubmit={handleSubmit}>
      {...fields and submit button here}
    </form>
  )
/>

Edit flamboyant-tesla-qozho

Upvotes: 1

Views: 2196

Answers (1)

jdkschang
jdkschang

Reputation: 65

I was able to pinpoint the source of the problem. I was leveraging the validate prop without mocking it in my tests. I solved this issue by mocking/ testing the validate function separately. Big thanks to @ErikR for the assistance 🙏🏻

Upvotes: 1

Related Questions