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.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!