Skip to main content

Lesson 8 of 8

Practice & Quiz - Testing React Apps

Test your knowledge of React Testing Library principles, MSW API mocking, testing hooks, and E2E testing with Playwright via a practical exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - Testing a Custom Hook with RTL + MSW

Practical Exercise - Testing a Custom Hook with RTL + MSW
// ─── usePosts.ts - the hook under test ───────────────────────
import { useQuery } from '@tanstack/react-query';

interface Post { id: number; title: string; }

export function usePosts() {
  return useQuery<Post[]>({
    queryKey: ['posts'],
    queryFn: () => fetch('/api/posts').then(r => {
      if (!r.ok) throw new Error('Failed to fetch');
      return r.json();
    }),
  });
}

// ─── posts.test.tsx - tests ───────────────────────────────────
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { usePosts } from './usePosts';

// ── MSW: intercept real fetch calls ───────────────────────────
const server = setupServer(
  http.get('/api/posts', () =>
    HttpResponse.json([
      { id: 1, title: 'First Post' },
      { id: 2, title: 'Second Post' },
    ])
  )
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

// ── Test wrapper - provides QueryClient ───────────────────────
function wrapper({ children }: { children: React.ReactNode }) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

// ── Component that uses the hook ──────────────────────────────
function PostList() {
  const { data, isLoading, isError } = usePosts();
  if (isLoading) return <p>Loading...</p>;
  if (isError)   return <p role="alert">Error loading posts</p>;
  return <ul>{data?.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}

// ─── Tests ────────────────────────────────────────────────────
describe('PostList', () => {
  it('shows loading state then renders posts', async () => {
    render(<PostList />, { wrapper });

    // Query by accessible role - the RTL way
    expect(screen.getByText('Loading...')).toBeInTheDocument();

    await waitFor(() => {
      expect(screen.getByText('First Post')).toBeInTheDocument();
      expect(screen.getByText('Second Post')).toBeInTheDocument();
    });
  });

  it('shows error state when API fails', async () => {
    // Override handler for this test only
    server.use(http.get('/api/posts', () => HttpResponse.error()));

    render(<PostList />, { wrapper });
    await waitFor(() => {
      expect(screen.getByRole('alert')).toHaveTextContent('Error loading posts');
    });
  });
});

// vitest.config.ts
// import { defineConfig } from 'vitest/config';
// export default defineConfig({ test: { environment: 'jsdom', globals: true, setupFiles: ['./src/test/setup.ts'] } });
Diagram
Loading diagram…

Modern React: Use Hooks instead of class lifecycle methods

Module Quiz

Module Quiz
Question 1 of 5

Why does React Testing Library prefer querying by role over by CSS class or ID?

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done