Testing React & Next.js Applications 2026: Complete Testing Guide
Master comprehensive testing strategies for React and Next.js applications. Learn unit testing, integration testing, and E2E testing with modern tools and best practices.
Full Stack Developer | Testing & Quality Assurance Expert
Why Testing Matters
Testing is essential for building reliable, maintainable applications. A comprehensive testing strategy catches bugs early, ensures code quality, and provides confidence when refactoring or adding new features.
In this guide, we'll explore the testing pyramid and implement unit, integration, and end-to-end tests for React and Next.js applications using modern tools.
The Testing Pyramid
The testing pyramid provides a framework for balancing different types of tests. It emphasizes having more unit tests at the base, fewer integration tests in the middle, and the fewest end-to-end tests at the top.
Unit Tests
Fast, isolated tests for individual functions and components
Integration Tests
Test how multiple units work together
E2E Tests
Test complete user flows in a browser
Unit Testing with Jest & React Testing Library
Unit tests are the foundation of your testing strategy. Jest provides the test runner and assertion library, while React Testing Library offers utilities for testing React components.
// Button.test.tsx
import { render, screen } from '@testing-library/react'
import { Button } from './Button'
describe('Button Component', () => {
it('renders button with correct text', () => {
render(<Button>Click me</Button>)
expect(screen.getByText('Click me')).toBeInTheDocument()
})
it('calls onClick handler when clicked', () => {
const handleClick = jest.fn()
render(<Button onClick={handleClick}>Click me</Button>)
screen.getByText('Click me').click()
expect(handleClick).toHaveBeenCalledTimes(1)
})
it('is disabled when disabled prop is true', () => {
render(<Button disabled>Click me</Button>)
expect(screen.getByText('Click me')).toBeDisabled()
})
})Unit Testing Best Practices
- Test user behavior, not implementation details
- Keep tests isolated and independent
- Use descriptive test names
- Follow AAA pattern (Arrange, Act, Assert)
- Avoid testing third-party libraries
Integration Testing
Integration tests verify that different parts of your application work together correctly. They're particularly useful for testing API routes, database interactions, and component integration.
// Integration test for API route
import { POST } from '@/app/api/users/route'
import { NextRequest } from 'next/server'
describe('User API Integration', () => {
it('creates a new user', async () => {
const request = new NextRequest('http://localhost:3000/api/users', {
method: 'POST',
body: JSON.stringify({ name: 'John', email: 'john@example.com' })
})
const response = await POST(request)
const data = await response.json()
expect(response.status).toBe(201)
expect(data.name).toBe('John')
expect(data.email).toBe('john@example.com')
})
})End-to-End Testing with Playwright
E2E tests simulate real user interactions in a browser. Playwright is a modern E2E testing framework that supports multiple browsers and provides excellent debugging capabilities.
// e2e/auth.spec.ts
import { test, expect } from '@playwright/test'
test.describe('Authentication Flow', () => {
test('user can login with valid credentials', async ({ page }) => {
await page.goto('http://localhost:3000/login')
await page.fill('input[name="email"]', 'user@example.com')
await page.fill('input[name="password"]', 'password123')
await page.click('button[type="submit"]')
await expect(page).toHaveURL('/dashboard')
await expect(page.locator('h1')).toContainText('Welcome')
})
test('shows error for invalid credentials', async ({ page }) => {
await page.goto('http://localhost:3000/login')
await page.fill('input[name="email"]', 'invalid@example.com')
await page.fill('input[name="password"]', 'wrongpassword')
await page.click('button[type="submit"]')
await expect(page.locator('.error')).toContainText('Invalid credentials')
})
})E2E Testing Best Practices
- Focus on critical user journeys
- Use data-testid selectors for stability
- Run tests in parallel for speed
- Use page object model for maintainability
- Integrate with CI/CD pipelines
Testing Next.js Specific Features
Next.js introduces unique features that require specific testing approaches, including Server Components, API routes, and middleware.
Server Components
Test Server Components by testing their rendered output and data fetching logic
API Routes
Test API routes directly using NextRequest and NextResponse
Middleware
Test middleware by mocking NextRequest objects
Route Handlers
Test different HTTP methods and status codes
Test Coverage & CI/CD
Measuring test coverage helps ensure your codebase is adequately tested. Integrating tests into CI/CD pipelines ensures code quality is maintained throughout development.
// package.json scripts
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui"
}
}
// .github/workflows/test.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- run: npm ci
- run: npm test
- run: npm run test:e2eConclusion
A comprehensive testing strategy is essential for building reliable React and Next.js applications. By combining unit tests, integration tests, and E2E tests, you can catch bugs early, ensure code quality, and ship with confidence. Remember that testing is an investment that pays dividends in maintainability and user satisfaction.