Testing 2 min read 942 views

Testing React Applications: Unit, Integration, and E2E Testing

Master React testing with Jest, React Testing Library, and Cypress. Learn best practices for unit, integration, and E2E tests.

Software testing

Testing React Applications

Build confidence in your code with comprehensive testing strategies.

Unit Testing with Jest

// utils.test.js
import { formatCurrency, calculateTotal } from './utils';

describe('formatCurrency', () => {
    it('formats positive numbers', () => {
        expect(formatCurrency(1234.56)).toBe('$1,234.56');
    });

    it('handles zero', () => {
        expect(formatCurrency(0)).toBe('$0.00');
    });
});

Component Testing with Testing Library

import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';

test('increments counter on click', async () => {
    render(<Counter />);

    expect(screen.getByText('Count: 0')).toBeInTheDocument();

    await userEvent.click(screen.getByRole('button', { name: /increment/i }));

    expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

Testing Async Operations

import { render, screen, waitFor } from '@testing-library/react';

test('loads and displays users', async () => {
    render(<UserList />);

    // Wait for loading to finish
    await waitFor(() => {
        expect(screen.queryByText('Loading...')).not.toBeInTheDocument();
    });

    // Check users are displayed
    expect(screen.getByText('John Doe')).toBeInTheDocument();
});

E2E Testing with Cypress

// cypress/e2e/login.cy.js
describe('Login Flow', () => {
    it('successfully logs in', () => {
        cy.visit('/login');
        cy.get('[data-testid="email"]').type('user@example.com');
        cy.get('[data-testid="password"]').type('password123');
        cy.get('button[type="submit"]').click();
        cy.url().should('include', '/dashboard');
        cy.contains('Welcome back').should('be.visible');
    });
});

Aim for a balanced testing pyramid: many unit tests, fewer integration tests, and minimal E2E tests.

Share this article:
ES
Written by

Edrees Salih

Full-stack software engineer with 9 years of experience. Passionate about building scalable solutions and sharing knowledge with the developer community.

View Profile

Comments (0)

Leave a Comment

Your email will not be published.

No comments yet. Be the first to share your thoughts!

Related Articles

Related Articles

Need Help With Your Project?

Book a free 30-minute consultation to discuss your technical challenges and explore solutions together.