Skip to main content
Testing queries and mutations requires proper setup of QueryClientProvider and handling of async behavior.

Basic Setup

Wrap your components in a QueryClientProvider for testing:

Testing Queries

Successful Query

Query Error

Testing Mutations

Successful Mutation

Mutation Error

Using MSW (Mock Service Worker)

MSW is recommended for API mocking:

Testing Hooks

Use renderHook from React Testing Library:

Testing with Prefetched Data

Set initial data in tests:

Testing Optimistic Updates

Testing Query Invalidation

Testing Suspense Queries

Custom Test Utilities

Create reusable test utilities:
Usage:

Testing Error Boundaries

Best Practices

  1. Always disable retry in tests for faster, predictable tests
  2. Use MSW for API mocking instead of manual fetch mocks
  3. Create test utilities for common setup
  4. Test all states - loading, success, error
  5. Use waitFor for async assertions
  6. Mock at the network level not the query level
  7. Test user interactions not implementation details

Common Pitfalls

1. Not Waiting for Async

2. Shared QueryClient

3. Not Cleaning Up

Next Steps