Created
February 11, 2026 18:51
-
-
Save claudiainbytes/b44cc7291178bf0fe7a57401cd2dd140 to your computer and use it in GitHub Desktop.
Testing de React Query / TanStack Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { QueryClient, QueryClientProvider } from '@tanstack/react-query' | |
| const createTestQueryClient = () => new QueryClient({ | |
| defaultOptions: { | |
| queries: { | |
| retry: false, // Deshabilitar reintentos en tests | |
| cacheTime: 0, | |
| }, | |
| }, | |
| }) | |
| const renderWithQuery = (ui) => { | |
| const queryClient = createTestQueryClient() | |
| return render( | |
| <QueryClientProvider client={queryClient}> | |
| {ui} | |
| </QueryClientProvider> | |
| ) | |
| } | |
| describe('ProductList with React Query', () => { | |
| it('carga productos con useQuery', async () => { | |
| renderWithQuery(<ProductList />) | |
| expect(screen.getByText(/loading/i)).toBeInTheDocument() | |
| await waitFor(() => { | |
| expect(screen.getByText('Product 1')).toBeInTheDocument() | |
| }) | |
| }) | |
| it('reintenta cuando falla', async () => { | |
| let attemptCount = 0 | |
| server.use( | |
| http.get('/api/products', () => { | |
| attemptCount++ | |
| if (attemptCount < 2) { | |
| return HttpResponse.error() | |
| } | |
| return HttpResponse.json([{ id: 1, name: 'Product 1' }]) | |
| }) | |
| ) | |
| const queryClient = new QueryClient({ | |
| defaultOptions: { | |
| queries: { retry: 1, retryDelay: 0 } | |
| } | |
| }) | |
| render( | |
| <QueryClientProvider client={queryClient}> | |
| <ProductList /> | |
| </QueryClientProvider> | |
| ) | |
| expect(await screen.findByText('Product 1')).toBeInTheDocument() | |
| expect(attemptCount).toBe(2) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment