Claude
Skills
Sign in
Back

jest-react-testing

Included with Lifetime
$97 forever

Comprehensive React component testing with Jest and React Testing Library covering configuration, mocking strategies, async testing patterns, hooks testing, and integration testing best practices

Design

What this skill does


# Jest React Testing

A comprehensive skill for testing React applications using Jest and React Testing Library. This skill covers everything from basic component testing to advanced patterns including mocking, async testing, custom hooks testing, and integration testing strategies.

## When to Use This Skill

Use this skill when:

- Testing React components with Jest and React Testing Library
- Setting up Jest configuration for React projects
- Writing unit tests for components, hooks, and utilities
- Testing user interactions and component behavior
- Mocking modules, functions, API calls, and external dependencies
- Testing asynchronous operations (API calls, timers, promises)
- Testing custom React hooks
- Writing integration tests for complex component trees
- Debugging failing tests or improving test coverage
- Following testing best practices and patterns

## Core Concepts

### Testing Philosophy

React Testing Library follows these guiding principles:

- **Test User Behavior, Not Implementation**: Write tests that resemble how users interact with your app
- **Accessibility First**: Use queries that promote accessible components (getByRole, getByLabelText)
- **Avoid Testing Implementation Details**: Don't test state, props, or internal methods directly
- **Maintainable Tests**: Tests should break when behavior changes, not when code refactors
- **Confidence Over Coverage**: Focus on tests that give confidence, not 100% coverage

### Key Testing Concepts

1. **Queries**: Methods to find elements (getBy, queryBy, findBy)
2. **User Events**: Simulating user interactions (click, type, select)
3. **Async Testing**: Testing components with asynchronous operations
4. **Mocking**: Replacing dependencies with controlled test doubles
5. **Assertions**: Verifying expected outcomes with matchers

## Jest Configuration

### Basic Jest Configuration

**jest.config.js** (JavaScript projects):
```javascript
/** @type {import('jest').Config} */
const config = {
  // Test environment for DOM testing
  testEnvironment: 'jsdom',

  // Setup files after environment
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],

  // Module paths
  moduleDirectories: ['node_modules', 'src'],

  // Transform files with babel-jest
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest',
  },

  // Module name mapper for static assets and CSS
  moduleNameMapper: {
    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|svg)$': '<rootDir>/__mocks__/fileMock.js',
  },

  // Coverage configuration
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!src/index.js',
    '!src/**/*.test.{js,jsx}',
    '!src/**/__tests__/**',
  ],

  // Coverage thresholds
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};

module.exports = config;
```

**jest.config.js** (TypeScript projects):
```typescript
import type {Config} from 'jest';

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],

  moduleDirectories: ['node_modules', 'src'],

  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },

  moduleNameMapper: {
    '\\.(css|less|scss|sass)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|svg)$': '<rootDir>/__mocks__/fileMock.ts',
    '^@/(.*)$': '<rootDir>/src/$1',
  },

  collectCoverageFrom: [
    'src/**/*.{ts,tsx}',
    '!src/index.tsx',
    '!src/**/*.test.{ts,tsx}',
    '!src/**/__tests__/**',
    '!src/**/*.d.ts',
  ],

  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};

export default config;
```

### Setup Files

**src/setupTests.js**:
```javascript
// Add custom jest matchers from jest-dom
import '@testing-library/jest-dom';

// Extend expect with jest-extended matchers (optional)
import * as matchers from 'jest-extended';
expect.extend(matchers);

// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: jest.fn().mockImplementation(query => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(),
    removeListener: jest.fn(),
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    dispatchEvent: jest.fn(),
  })),
});

// Mock IntersectionObserver
global.IntersectionObserver = class IntersectionObserver {
  constructor() {}
  disconnect() {}
  observe() {}
  takeRecords() {
    return [];
  }
  unobserve() {}
};

// Suppress console errors in tests (optional)
const originalError = console.error;
beforeAll(() => {
  console.error = (...args) => {
    if (
      typeof args[0] === 'string' &&
      args[0].includes('Warning: ReactDOM.render')
    ) {
      return;
    }
    originalError.call(console, ...args);
  };
});

afterAll(() => {
  console.error = originalError;
});

// Reset mocks after each test
afterEach(() => {
  jest.clearAllMocks();
});
```

### File Mocks

**__mocks__/fileMock.js**:
```javascript
module.exports = 'test-file-stub';
```

**__mocks__/styleMock.js**:
```javascript
module.exports = {};
```

## React Testing Library Queries

### Query Types

React Testing Library provides three types of queries:

1. **getBy**: Returns element or throws error (use for elements that should exist)
2. **queryBy**: Returns element or null (use for elements that may not exist)
3. **findBy**: Returns promise that resolves to element (use for async elements)

### Query Priority

**Recommended Query Order** (accessibility-focused):

1. **getByRole**: Most accessible query
   ```javascript
   getByRole('button', { name: /submit/i })
   getByRole('heading', { level: 1 })
   getByRole('textbox', { name: /username/i })
   ```

2. **getByLabelText**: For form fields with labels
   ```javascript
   getByLabelText(/email address/i)
   getByLabelText('Password')
   ```

3. **getByPlaceholderText**: For inputs with placeholders
   ```javascript
   getByPlaceholderText(/search/i)
   ```

4. **getByText**: For non-interactive elements with text
   ```javascript
   getByText(/welcome/i)
   getByText('Error: Invalid credentials')
   ```

5. **getByDisplayValue**: For form elements with values
   ```javascript
   getByDisplayValue('John Doe')
   ```

6. **getByAltText**: For images with alt text
   ```javascript
   getByAltText(/profile picture/i)
   ```

7. **getByTitle**: For elements with title attribute
   ```javascript
   getByTitle(/close/i)
   ```

8. **getByTestId**: Last resort when other queries don't work
   ```javascript
   getByTestId('custom-element')
   ```

### Query Variants

```javascript
// Single element queries
screen.getByRole('button')      // Throws if not found or multiple found
screen.queryByRole('button')    // Returns null if not found
await screen.findByRole('button') // Async, waits up to 1000ms

// Multiple element queries
screen.getAllByRole('listitem')      // Throws if none found
screen.queryAllByRole('listitem')    // Returns [] if none found
await screen.findAllByRole('listitem') // Async version
```

## Component Testing Strategies

### Basic Component Test

```javascript
import { render, screen } from '@testing-library/react';
import { Greeting } from './Greeting';

describe('Greeting Component', () => {
  it('renders greeting message', () => {
    render(<Greeting name="Alice" />);

    expect(screen.getByText(/hello, alice/i)).toBeInTheDocument();
  });

  it('renders default greeting when no name provided', () => {
    render(<Greeting />);

    expect(screen.getByText(/hello, guest/i)).toBeInTheDocument();
  });
});
```

### Testing User Interactions

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

describe('Counter Component', () => {
  it('increments counter on button click', async () => {
    const user = userEvent.setup();
    render(<Counter />);

    const button = screen.getByRole('button', { n

Related in Design