how to debug a test timing out waiting for React.lazy import

Viewed 81

I have a React+vite app for which I'm writing test to cover the front-end routing redirection logic at application startup.

Routing is handled by react-router v6, and all components associated with routes are wrapped in React.lazy. Tests are ran by vitest and I'm using react-testing-library helpers

All the tests are similar and look like this

it('Redirects from app root to red room if the user has a red shirt', async () => {
    getUser.mockReturnValue(redShirtUser);
    render(MyTestedComponent, { wrapper });

    await waitFor(() => expect(screen.getByText('Welcome to the red room'));
    expect(history.location.pathname).toBe('/red-room');
  });

One of the tests, though, is taking significantly longer than the others, to the point that waitFor times out. I can specify a longer timeout to waitFor, but it will still not reliably run on the CI. This happens also if the test is the only one in its file/the only one being executed.

I have narrowed down the slow part (through the magic of console.log debugging) to be the lazy import() statement - it takes a lot (seconds) until the module is imported and executed.

How can I debug this? Are there things known to cause (lazy) imports to become slow?

1 Answers

Version before 10 we can use waitForElement, it will take less time.For more details or detailed explanation watch this https://www.youtube.com/watch?v=lfb5jvHq9c4 video. After version 10 whatever you used waitFor is correct.Thanks for correcting @agos.Editing comment to save other users from trouble. But along with that Making sure to use proper error handling in that component using try catch is equally important.

Related