Search code examples
javascriptjestjsreact-testing-library

React Testing Library testing for the saving state of a button


I have a button that briefly changes text to the text Saving when clicked. How can I test for this state? I suspect the name change happens so quickly it is not being picked up rather than it being broken.

await act(() => {
  const saveButton = screen.getByRole("button", { name: "Save" });
  fireEvent.click(saveButton);
  expect(saveButton).toHaveAttribute("name", "Saving");
});

Can this be done without simulating a slow down in the API request?


Solution

  • Try to put the expect() and saveButton out from act().

    const saveButton = screen.getByRole("button", { name: "Save" });
    
    await act(() => {
      fireEvent.click(saveButton);
    });
    
    expect(saveButton).toHaveAttribute("name", "Saving");
    

    When the expect() is in the act() it does not wait for the fireEvent.click(saveButton).

    Note:

    On the intro example, it does not use the act() for user event, just transforms the test() to an async function and uses await for user events before the assertions.