Search code examples
reactjstypescriptreact-testing-libraryvitest

Testing Library with React navigation not works as expected


In my header there is cart icon. when user click on cart icon it takes to 'cart page'. I and testing the cart icon click event. But getting null from the cart page.

here is my test for header:

import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { BrowserRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { renderWithProviders } from "./../../../utils/utils-for-tests";
import Header from "./Header";

describe("header component", () => {
  it("should redirect to cart page on click of cart button", async () => {
    await renderWithProviders(
      <BrowserRouter>
        <Header />
      </BrowserRouter>
    );
    const user = userEvent.setup();
    const cartIcon = screen.queryByText(/Cart/) as Element; //header component
    expect(cartIcon).toBeInTheDocument();
    await user.click(cartIcon);
    await waitFor(async () => {
      const cart = screen.queryByText(/Shopping Cart/i) as Element; //shopping cart page
      console.log("cart", cart); //null
    });
  });
});

Here is the sample live demo


Solution

  • I have updated my code in to follows. it works fine.

    import { describe, it, expect, beforeAll } from "vitest";
    import { screen, render } from "@testing-library/react";
    import { user } from "@testing-library/user-event";
    import Header from "./Header";
    import user from "@testing-library/user-event";
    import { MemoryRouter, Routes, Route } from "react-router-dom";
    import { Products } from "../Products/Products";
    
    describe("Header component testings", () => {
      beforeAll(() => {
        render(
          <MemoryRouter>
            <Routes>
              <Route path="/" element={<Header />} />
              <Route path="/products" element={<Products />} />
            </Routes>
          </MemoryRouter>,
        );
      });
    
      it("should render header component", async () => {
        const h1 = await screen.queryByText("Welcome to app");
        expect(h1).toBeInTheDocument();
      });
    
      it("should render header component", async () => {
        user.click(screen.getByRole("link", { name: "Go to products" }));
        expect(await screen.findByText("Products page")).toBeInTheDocument();
      });
    });