Testing Loading States
What you'll learn: How to verify that loading indicators appear instantly and then properly disappear when data arrives, giving users confidence in what they see while waiting.
Why Loading States Matter
When your component fetches data, users should see a loading indicator immediately—not a blank screen or stale content. Testing that this indicator appears right away, then vanishes when data loads, ensures your users always know what's happening.
The Two-Phase Pattern
Loading state tests follow a simple rhythm:
- Assert the loading indicator appears immediately using
getByorqueryBy - Wait for it to disappear when data arrives using
findByqueries
test('shows loading spinner while fetching user data', async () => {
render(<UserProfile userId="123" />);
// Phase 1: Loading indicator should appear right away
expect(screen.getByText(/loading/i)).toBeInTheDocument();
// Phase 2: Wait for the indicator to disappear
// findBy automatically waits and retries
const userName = await screen.findByText(/john doe/i);
expect(userName).toBeInTheDocument();
// Loading indicator should be gone now
expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});
Why This Approach Works
The findBy query waits for the async operation to complete—it keeps checking until the element appears (up to a timeout). This naturally waits for your data fetch to finish. Once data renders, you verify the loading state has been replaced with real content.
Think of it like watching a traffic light: you confirm it turns red immediately, then wait for it to turn green again. Both phases matter.
Key Takeaway: Test loading states by asserting the indicator appears synchronously with getBy, then use findBy to wait for actual content—confirming the loading state disappears when data arrives.