1

I am trying to write a test for when a react-hot-toast appears. Currently in my app, when you click a button, a react hot toast appears. It is visible on screen and within the inspect window, and after a few seconds it will disappear from view and from the inspect window

inspect window of toast message

However I cant seem to find it when trying to test that it appears. Currently I have the following code to test that it appears when a button is clicked:

test("get info with no id entered", async () => {
  render( <Student /> );
  const infoButton = screen.getByRole("button", { name: /get info/i });
  userEvent.click(infoButton);
  const toastText = await screen.findByRole("status", {name: /please enter an id/i});
  expect(toastText).toBeInTheDocument();
});

I keep receiving the error that toastText cannot be found, despite it appearing in the inspect window. Any help is appreciated!

Brian
  • 149
  • 1
  • 12

1 Answers1

0

Try using findByText instead of role, sometimes react testing library does not accept these roles.

When I had this issue, I solved mine by using a settimeout to wait for the actual text to be available on the dom.

Solution 1:

test("get info with no id entered", async () => {
  render( <Student /> );
  const infoButton = screen.getByRole("button", { name: /get info/i });
  userEvent.click(infoButton);
  const toastText = await screen.findByText(/please enter an id/i});
  expect(toastText).toBeInTheDocument();
});

Solution 2:

test("get info with no id entered", async () => {
  render( <Student /> );
  const infoButton = screen.getByRole("button", { name: /get info/i });
  userEvent.click(infoButton);
  setTimeout(() => {
        expect(screen.getByText('please enter an id')).toBeInTheDocument()
   }, 2000);
});
Esther
  • 1
  • 1