0
0
ReactHow-ToBeginner · 4 min read

How to Use Jest with React: Simple Testing Guide

To use Jest with React, install Jest and React Testing Library, then write test files using describe and test blocks to check component behavior. Run tests with the jest command or npm test to see results.
📐

Syntax

Jest tests for React use describe to group tests and test or it to define individual test cases. Use render from React Testing Library to render components, and expect to assert outcomes.

  • describe(): Groups related tests.
  • test(): Defines a single test case.
  • render(): Renders React component for testing.
  • expect(): Checks if the result matches expected value.
javascript
import React from 'react';
import { render, screen } from '@testing-library/react';

describe('ComponentName', () => {
  test('renders correctly', () => {
    render(<ComponentName />);
    expect(screen.getByText('Hello')).toBeInTheDocument();
  });
});
💻

Example

This example shows a simple React component and a Jest test that checks if the component renders the expected text.

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

function Greeting() {
  return <h1>Hello, Jest!</h1>;
}

describe('Greeting component', () => {
  test('displays greeting message', () => {
    render(<Greeting />);
    const message = screen.getByText('Hello, Jest!');
    expect(message).toBeInTheDocument();
  });
});
Output
PASS ./Greeting.test.js Greeting component ✓ displays greeting message (20 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.5 s
⚠️

Common Pitfalls

Common mistakes include not installing @testing-library/jest-dom for extra matchers, forgetting to import render or screen, and testing implementation details instead of user-visible output. Avoid testing internal state or methods directly; focus on what the user sees.

javascript
/* Wrong: Testing internal state directly */
// expect(component.state.value).toBe('test');

/* Right: Testing visible output */
// expect(screen.getByText('test')).toBeInTheDocument();
📊

Quick Reference

  • Install dependencies: npm install --save-dev jest @testing-library/react @testing-library/jest-dom
  • Use render() to mount components in tests.
  • Use screen to query elements as users would.
  • Use expect(...).toBeInTheDocument() to check presence.
  • Run tests with npm test or jest.

Key Takeaways

Install Jest and React Testing Library to test React components effectively.
Use render and screen from React Testing Library to interact with components in tests.
Write tests focusing on user-visible output, not internal implementation.
Run tests using npm test or the jest command.
Avoid common mistakes like missing imports or testing internal state directly.