I'm working with a custom React component that wraps an Office UI Fabric TextField within a Formik form. Despite following typical patterns for handling input fields with React and Formik, I'm encountering issues when testing the component using React Testing Library. The input's value does not update after simulating a change event in Jest.
Here's the relevant part of my component:
const FMIconButtonTextField: React.FC<Props> = props => {
const { label, styles, name, callOutSpanText } = props;
const [isCalloutVisible, setIsCalloutVisible] = useState(false);
const inputId = getId(name);
const [field, { touched, error }] = useField(name);
return (
<>
<TextField
{...field}
{...props}
label={label}
errorMessage={touched && error ? error : null}
id={inputId}
/>
</>
);
};
And here's how I'm testing it:
it('allows input into the voucher code field', async () => {
const initialValues = { voucherCode: '' };
const { container, findByDisplayValue } = render(
<Formik initialValues={initialValues} onSubmit={jest.fn()}>
<Form>
<FMIconButtonTextField
name="voucherCode"
label="Voucher Code *"
callOutSpanText="Voucher Code must contain at least 5 characters and no more than 20 characters, and is allowed A to Z, 0 to 9, and _."
placeholder="Only A-Z or 0-9 or _"
/>
</Form>
</Formik>
);
const input = container.querySelector('input[name="voucherCode"]');
fireEvent.change(input, { target: { value: 'ABC123' } });
// Wait for React's state update to propagate
await findByDisplayValue('ABC123'); // This ensures the input has received and displays the new value
expect(input.value).toBe('ABC123');
});
Despite these efforts, the test fails with the input value not updating:
expect(received).toBe(expected) // Object.is equality
Expected: "ABC123"
Received: ""