I’m using storybook-test-runner on Windows 10 with the latest Chrome. I want to wait for asynchronous component loading using WaitFor, but the function doesn’t pause as expected. Tests fail with “element not found” errors, even though the element should be visible. I need guidance on properly using WaitFor so tests wait reliably for elements to appear.
The issue often comes from the default timeout being too short. WaitFor polls a condition until it’s true, but if your component takes longer to load than the default timeout, tests fail prematurely.
Example of a working approach:
await waitFor(() => expect(screen.getByText('Your Element')).toBeInTheDocument(), { timeout: 5000 });
This waits up to 5 seconds for the element. Make sure you are checking the correct condition and use logging or debugging tools in storybook-test-runner to observe asynchronous behavior.
Sometimes the problem is inaccurate selectors. Elements may exist but not match your selector due to dynamic classes or structural changes. Verify your selectors using browser dev tools.
Example:
await waitFor(() => {
const element = document.querySelector('.my-class');
if (element) {
expect(element.textContent).toBe('Loaded');
}
});
Also, ensure polyfills and setup files are correctly loaded in your test runner configuration, especially across different environments.