Search code examples
react-testing-libraryprimereact

"userEvent.click" doesn't trigger expected changes on this unit test


I have this simple example where I'm trying to write a test for component containing Primereact Dropdown. But even the mouse click shows the panel with options, I can't get options in my test.

For quick review, I'm placing the test here as well:

import {
  render,
  act,
  fireEvent,
  waitFor,
  screen
} from "@testing-library/react";
import "@testing-library/jest-dom";
import userEvent from "@testing-library/user-event";

import GroupedDemo from "../src/App";

describe("Test App Component", () => {
  it("Primereact dropdown", async () => {
    const { container } = render(<GroupedDemo />);
    await userEvent.click(screen.getAllByText("Select a City")[1]);
    expect(container.querySelector(".p-dropdown-panel")).not.toBeNull();
  });
});

Thank you


Solution

  • So after some time spent deeper with it and react testing library documentation I came up with this repository where I have set of simple unit tests to confirm UX functionality.

    github.com/dominikj111/UXConfirmationTests

    Surely, I didn't know how to use the tool before, but I'm going to comment those mentioned here.

    • waitFor is for to wait for your expectations to pass (doc).
    • Sometimes we need to wait for an element what disappearing because of fading animation (doc).
    • The other problem I had was misunderstanding the returned value of the queries.
    • For some reason, I can't inspect the DOM from the container returned by the render method, (please, see this in doc)(this is something I'm going to investigate in near future again). Anyway, to debug your test and see the DOM structure, check this out. Something like this screen.queryByText("Group 1").parentElement.parentElement.parentElement.querySelector("[role='checkbox']") works well. getByRole doesn't work :-( (I'll need to review this as well)

    This fixed test in the example of my question above works well:

      render(<GroupedDemo />);
    
      expect(screen.queryByText("Chicago")).toBeNull();
      expect(screen.queryByText("Los Angeles")).toBeNull();
    
      fireEvent.click(screen.getAllByText("Select a City")[1]);
    
      expect(screen.queryByText("Chicago")).not.toBeNull();
      expect(screen.queryByText("Los Angeles")).not.toBeNull();