I am using Form in react. It has card number field. So if the user enters "333" and enters a tab, there is a dynamic message which shows up saying, "Card number needs to be a 16 digit number".
I am writing tests using @testing-library/react@9.5.0 and ts-jest@26.3.0.
Form Component:
CardForm.ts
users React-text-mask, Material UI to show an input which does validation by a schema which has a method to see if the input value is 16 or not and returns an error which is then displayed as helper text.
<form onSubmit={handleSubmit}>
<FormInput
name="cardNumber"
label="Card Number"
inputMode="numeric"
value={values.cardNumber}
placeholder="XXXX-XXXX-XXXX-XXXX"
validation={validationSchema.cardNumber}
mask={formMasks.cardNumber}
/>
<Button
type="submit"
disabled={!values.card || validationSchema.cardNumber.errors.length === 0}
>
CONFIRM CARD
</Button>
</form>
CardForm.test.tsx
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { CardForm } from '../components/Forms/CardForm';
const setup = () => {
const utils = render(<CardEmailForm />);
const input = utils.getByPlaceholderText('XXXX-XXXX-XXXX-XXXX');
return {
input,
...utils,
};
};
test('show error message when card number entered is less than 16 digits', async () => {
const { input, ...utils } = setup();
fireEvent.change(input, {
target: { value: '333' }, // I am giving the value 333 to the input
});
expect((input as HTMLInputElement).value).toBe('333 - - - '); //works
/* if I lose focus from the input, the error message shows up as helper text at the bottom of the input as shown above */
fireEvent.blur(input);
/* now I am just expecting to read the error from the DOM based on h6 helper text, but this keeps giving me ERROR. */
expect(await utils.getByRole('heading')).toHaveTextContent(
'Card Number should be 16 numbers'
);
});
> 29 | await screen.getByRole('heading');
| ^
30 | expect(screen.getByRole('heading')).toHaveTextContent(
31 | 'Card Number should be 16 numbers'
32 | );
at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:34:12)
at getMultipleElementsFoundError (node_modules/@testing-library/dom/dist/query-helpers.js:21:35)
Can someone help me write the expect statement so that once I give wrong input and then blur, I am able to read the error off the screen?

