0

I am displaying a loading indicator whilst I wait for an async process to occur, however I believe my test might be missing it being displayed because the async process is too quick?

const [isLoading, setIsLoading] = useState(false);

const handleClick = async () => {
  setIsLoading(true); // Show loader when waiting for url to be fetched
  await getAsyncRedirectUrl().then(url => {
    setIsLoading(false); // Hide loader when url fetched
    window.open(url);
  })
}

return (
  <>
    {isLoading && <LoadingIndicator data-testid="loader" />}
    <button onClick={handleClick} data-testid="button">Click me</button>
  </>
)

I have tried to test with the following, to no avail.

it('should show loader', async () => {
  render(<MyComponent />);

  await userEvent.click(screen.queryByTestId('button'));

  await waitFor(() => {
    expect(screen.queryByTestId('loader')).toBeInTheDocument();
  });  
});

The outcome of this test is a failure stating that the loader wasn't found within the DOM.

I added an artificial wait on the function with a setTimeout of 100ms and the test passed. So that would indicate to me that the getAsyncRedirecUrl function is simply finishing too quickly for the test to be able to register the loader as being shown.

3
  • Are you sure that <LoadingIndicator> accepts data-testid prop and populates it on a DOM element? Probably related: stackoverflow.com/questions/75659831/… Commented Jan 31 at 9:02
  • @HaoWu that part is a bit psuedo-code. The test ID is actually hardcoded on the component itself, this was just for visibility. Commented Jan 31 at 9:04
  • can you mock getAsyncRedirectUrl and control when it is resolved manually. so that you can test the intermediate states ? Commented Jan 31 at 9:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.