OiO.lk Blog javascript React testing library not work with react router v6
javascript

React testing library not work with react router v6


I have several unit tests that test form validation for my login screen.

Example:

test("Invalid email renders error", async () => {
  render(<LoginForm />);

  // Arrange
  const emailElement = screen.getByTestId("email");
  const passwordElement = screen.getByTestId("password");
  const submit = screen.getByTestId("login-button");

  // Act
  await user.type(emailElement, "invalid");
  await user.type(passwordElement, "1234567890");
  fireEvent.click(submit);

  // Assert
  await waitFor(() => {
    expect(screen.getByText("Invalid email format")).toBeInTheDocument();
  });
});

But when I add this Link it fails:

<p>
  Don't have an account? <Link to="/Register">Register here</Link>
</p>
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

  88 |   test("Button was called with form values", async () => {
  89 |     const consoleSpy = jest.spyOn(console, "log");
> 90 |     render(<LoginForm />);
     |           ^
  91 |     //Arrange
  92 |     const emailElement = screen.getByTestId("email");
  93 |     const passwordElement = screen.getByTestId("password");

Any idea why the link text is causing this failure?

Here are the routes

function App() {
  return (
    <Routes>
      <Route path="/" element={<LoginForm />} />
      <Route path="Register" element={<RegisterForm />} />
    </Routes>
  );
}



You need to sign in to view this answers

Exit mobile version