I am not able to test for proper validation of a form with React-bootstrap. I want to see that when the input pattern is not valid, the invalid feedback text is displayed once the form is validated.
Working codesandbox with tests: https://codesandbox.io/s/flamboyant-cerf-7t7jq
import React, { useState } from "react";
import { Form, Button, InputGroup } from "react-bootstrap";
export default function App(): JSX.Element {
const [validated, setValidated] = useState<boolean>(false);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setValidated(true);
};
return (
<Form
className="col-12 col-lg-5 trans-form"
noValidate
validated={validated}
onSubmit={handleSubmit}
>
<InputGroup className="my-2">
<InputGroup.Prepend>
<InputGroup.Text>Receiver Public Key</InputGroup.Text>
</InputGroup.Prepend>
<Form.Control
role="textbox"
className="text-truncate rounded-right"
type="text"
pattern="[A-Za-z0-9]{5}"
required
/>
<Form.Control.Feedback
className="font-weight-bold"
type="invalid"
role="alert"
>
Length or format are incorrect!
</Form.Control.Feedback>
</InputGroup>
<Button
role="button"
className="mt-2 font-weight-bold"
variant={"primary"}
type="submit"
block
>
Sign
</Button>
</Form>
);
}
Tests
import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import App from "../src/App";
describe("form validation", () => {
test("invalid receiver public key length", async () => {
render(<App />);
userEvent.click(screen.getByRole("button"));
userEvent.type(screen.getByRole("textbox"), "invalid");
expect(screen.getByRole("textbox")).toHaveValue("invalid");
expect(
await screen.findByText("Length or format are incorrect!")
).toBeVisible();
});
// this test fails, making it seem like the invalid-feedback is always present
test("valid receiver public key length", async () => {
render(<App />);
userEvent.click(screen.getByRole("button"));
userEvent.type(screen.getByRole("textbox"), "valid");
expect(screen.getByRole("textbox")).toHaveValue("valid");
await waitFor(() => {
expect(
screen.queryByText("Length or format are incorrect!")
).not.toBeVisible(); // ← FAILS
});
});
});
Result
Second test fails with