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
TextField
with some common functions that meet the business requirements - It is an adaptor bridging the RHF forms and
mui
so that the form components do not dependmui
, which made upgrading or replacingmui
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
- It inherits all the behaviours from
TextField
ofmui
and accepts allTextField
props as-is. - It takes
name
,formContext
anddefaultValue
required props and registers theTextField
to 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
hidden
is true. - It builds in the
required
validation rule and takes arequired
prop. - It accepts validation rules and enforces them.
- It formats numbers with thousands separator commas by default and accept
numericProps
of typeNumberFormatProps
fromreact-number-format
for further customisation. - It defaults to size small.
- It takes an optional
onChange
prop. On change, it will trigger the givenonChange
method and update input value.
Code
Notes
-
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. - For good orders, the tests are grouped into four categories: appearance, behaviours, validations and number formatting.
- Appearance tests depend on how
mui
renders itsTextField
and assert the class names rendered bymui
. - Validation tests depend on RHF's validations and the render helper text of
TextField
. - The tests use
userEvent
to mimic end-user browser interactions. -
onSubmit
is mocked and cleared before each test. -
EpicTextField
is a styledTextField
with@emotion/styled
Top comments (0)