DEV Community

Rex
Rex

Posted on • Updated on

Testing a Text Field component integrating Mui's Text Field with React Hook Form

Subject Under Test

An input component integrating TextFeild of mui with React Hook Form. It uses the Controller component from React Hook Form(RHF) and configures TextField to handle validations and more. I use this component instead of TextField from mui in all my forms. There are three benefits to this approach(adaptor pattern):

  1. It provides RHF integration
  2. It is a customised version of TextField with some common functions that meet the business requirements
  3. It is an adaptor bridging the RHF forms and mui so that the form components do not depend mui, which made upgrading or replacing mui very easy.

Target Users

The SUT's target users are developers, and it is to be used inside an RHF form only. Therefore the behaviours and tests are focused on the expectations of the developers.

Behaviours

  1. It inherits all the behaviours from TextField of mui and accepts all TextField props as-is.
  2. It takes name, formContext and defaultValue required props and registers the TextField to the form context of RHF
  3. It has two modes: edit mode and read-only mode. In read-only mode, it is disabled and rendered as a standard(underline) TextField. In edit mode, it is rendered as outlined TextField.
  4. It hides if hidden is true.
  5. It builds in the required validation rule and takes a required prop.
  6. It accepts validation rules and enforces them.
  7. It formats numbers with thousands separator commas by default and accept numericProps of type NumberFormatProps from react-number-format for further customisation.
  8. It defaults to size small.
  9. It takes an optional onChange prop. On change, it will trigger the given onChange method and update input value.

Code

Notes

  1. TestComponent shows the usage of the SUT. Its props are extended from the SUT's props so that the tests can configure the SUT on the fly.
  2. For good orders, the tests are grouped into four categories: appearance, behaviours, validations and number formatting.
  3. Appearance tests depend on how mui renders its TextField and assert the class names rendered by mui.
  4. Validation tests depend on RHF's validations and the render helper text of TextField.
  5. The tests use userEvent to mimic end-user browser interactions.
  6. onSubmit is mocked and cleared before each test.
  7. EpicTextField is a styled TextField with @emotion/styled

Top comments (0)