How to wait until button's disabled state is changed in testing library?

Viewed 4682

I have a React component with a input field and a button disabled at the very beginning. This button's state ( disabled ) changes if input provided by user to input field is validated by API, which is called after anything is typed in input field.

I am testing by providing a valid input but it needs to wait until API's call is completed, so basically i want to test, if on providing a valid input, button get re enabled or not in my test.

I am doing this by following code:

userEvent.type(getByRole("textbox"), "HELLO");
await waitFor(() => expect(getByTestId("my-btn")).not.toBeDisabled());

But its not working even with a valid input

2 Answers

You can increase the waitFor timeout as explained in the doc:

await waitFor(() => expect(getByTestId("my-btn")).not.toBeDisabled(), {
  timeout: 5000,
});

Beyond 5000 you will probably need also to increase jest timeout.

For me waiting for a disabled state to dissapear doesn't work. I usually wait for something else to happen in the DOM.

Maybe using the input you typed something in...

userEvent.type(getByRole("textbox"), "HELLO");

expect(await expect(screen.getByDisplayValue('HELLO')).toBeInTheDocument()); 

expect(getByTestId("my-btn")).not.toBeDisabled()

Also, since you are waiting for the response of an API, you might want to mock the response of that call to something that will remove your disabled state.

Related