Reputation: 1665
I am trying to write a RTL test for my validations on my form. I am using useForm
hook with Yup
fro my validations.
The scenario i want to test is when user clicks the Add
button that submits the from without filling in all the required fields (title and description). In that scenario some error messages will pop up under the empty inputs on the from. It is these messages i want to test fro.
I have written the test where i am finding the title, description and Add button but when i click the add button and do screen.debug()
the error messages are not there.
Form input snipped:
<div className="Form__title">
<label className="Form__title--label" htmlFor="title">
Title
</label>
<input
{...register("title")}
type="text"
placeholder="Title..."
data-testid="titleInput"
/>
{errors?.title && (
<p data-testid="titleError">{errors.title.message}</p>
)}
</div>
My test:
test("throws title must be at least 1 characters", async () => {
renderWithProviders(<TileForm />);
const error = "title must be at least 1 characters";
const addNewIdeaButton = screen.getByText("Add New Idea");
await userEvent.click(addNewIdeaButton);
const descriptionInput = screen.getByTestId("descriptionInput");
await userEvent.type(descriptionInput, "foo");
const addButton = screen.getByText("Add");
await userEvent.click(addButton);
screen.debug();
expect(screen.getByTestId("titleError")).toBeInTheDocument();
// expect(screen.getByTestId("titleError")).toHaveValue(error);
});
Not to sure what i am missing, seems like when i click the button it does not submits the form hence why the error messages are not showing.
It is these red messaged that i want to test for:
Upvotes: 1
Views: 3135
Reputation: 1665
For anyone that faces such or similar issue the problems is this:
when you submit the form it is a async call and it will take some time for the validation errors to pop up.
to fix this you will need to wrap your expectation in waitFor
. which will wait for the expected item to appear in the DOM before asserting it
await waitFor(async () => {
expect(await screen.findByText(titleError)).toHaveTextContent(
titleError
);
});
Upvotes: 5