React Testing Library for component tests
Maya Patel
Jan 2026
2 tabs
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { PostCard } from '../PostCard'
import { Post } from '@/types'
const mockPost: Post = {
id: '1',
title: 'Test Post',
body: 'This is a test post',
excerpt: 'This is a test',
status: 'published',
published_at: '2024-01-15T10:00:00Z',
created_at: '2024-01-15T10:00:00Z',
updated_at: '2024-01-15T10:00:00Z',
author: {
id: '1',
name: 'John Doe',
email: 'john@example.com',
avatar_url: null,
},
tags: ['react', 'testing'],
comments_count: 5,
likes_count: 10,
}
describe('PostCard', () => {
it('renders post information', () => {
render(<PostCard post={mockPost} />)
expect(screen.getByRole('heading', { name: 'Test Post' })).toBeInTheDocument()
expect(screen.getByText('This is a test')).toBeInTheDocument()
expect(screen.getByText('John Doe')).toBeInTheDocument()
expect(screen.getByText('10')).toBeInTheDocument() // likes count
})
it('navigates to post detail when title is clicked', async () => {
const user = userEvent.setup()
render(<PostCard post={mockPost} />)
const titleLink = screen.getByRole('link', { name: 'Test Post' })
await user.click(titleLink)
// Assert navigation occurred (with router mock)
})
it('shows tags', () => {
render(<PostCard post={mockPost} />)
expect(screen.getByText('react')).toBeInTheDocument()
expect(screen.getByText('testing')).toBeInTheDocument()
})
})
import '@testing-library/jest-dom'
import { server } from './mocks/server'
// Establish API mocking before all tests
beforeAll(() => server.listen())
// Reset handlers after each test
afterEach(() => server.resetHandlers())
// Clean up after tests
afterAll(() => server.close())
2 files · typescript
Explain with highlit
Testing Library encourages testing components from the user's perspective rather than implementation details. I query elements by accessible labels, text content, or roles—not by CSS classes or test IDs. User interactions use userEvent to simulate realistic behavior like typing and clicking. Async queries like findBy wait for elements to appear, perfect for testing loading states. I mock API calls with MSW (Mock Service Worker) to test component behavior with realistic data. Tests focus on what users see and do, making them resilient to refactors. This philosophy catches real bugs while avoiding brittle tests that break on internal changes.