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):
- It provides RHF integration
- It is a customised version of
TextFieldwith some common functions that meet the business requirements - It is an adaptor bridging the RHF forms and
muiso that the form components do not dependmui, which made upgrading or replacingmuivery 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
- It inherits all the behaviours from
TextFieldofmuiand accepts allTextFieldprops as-is. - It takes
name,formContextanddefaultValuerequired props and registers theTextFieldto the form context of RHF - 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 outlinedTextField. - It hides if
hiddenis true. - It builds in the
requiredvalidation rule and takes arequiredprop. - It accepts validation rules and enforces them.
- It formats numbers with thousands separator commas by default and accept
numericPropsof typeNumberFormatPropsfromreact-number-formatfor further customisation. - It defaults to size small.
- It takes an optional
onChangeprop. On change, it will trigger the givenonChangemethod and update input value.
Code
Notes
-
TestComponentshows 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. - For good orders, the tests are grouped into four categories: appearance, behaviours, validations and number formatting.
- Appearance tests depend on how
muirenders itsTextFieldand assert the class names rendered bymui. - Validation tests depend on RHF's validations and the render helper text of
TextField. - The tests use
userEventto mimic end-user browser interactions. -
onSubmitis mocked and cleared before each test. -
EpicTextFieldis a styledTextFieldwith@emotion/styled
Top comments (0)