TExcelTAD
Home › React › React Testing

React Testing

Tests let you change code with confidence: if a refactor breaks a feature, a test tells you before your users do. In React projects the most common setup is Vitest (a fast test runner that shares Vite's config) plus React Testing Library (RTL), which renders components and lets you interact with them the way a user would.

Note: Test runners run in Node with a simulated DOM, so they can't run in these playgrounds. The terminal output below is simulated; the pure-JavaScript examples are real and runnable.

Setting up

bash · try it yourself
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
added 96 packages, and audited 249 packages in 6s

found 0 vulnerabilities

Tell Vitest to use a browser-like environment, and add a script:

js
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    setupFiles: './src/setupTests.js',   // contains: import '@testing-library/jest-dom/vitest';
  },
});
json
{ "scripts": { "test": "vitest" } }

The testing pyramid for React

Level What you test Tools
Unit pure functions: reducers, formatters, validators Vitest
Component one component's behaviour: renders, clicks, typing Vitest + React Testing Library
End-to-end real browser, real app, whole user flows Playwright, Cypress

Write many fast unit tests, a good number of component tests, and a few end-to-end tests for critical paths such as checkout or login.

Unit testing pure logic

Reducers and helpers are plain functions, so they're the easiest code to test. Here is the idea with a tiny hand-written test/expect (Vitest provides real ones with the same shape):

js · try it yourself
// --- a minimal test harness (Vitest gives you this for free) ---
let passed = 0, failed = 0;
function test(name, fn) {
  try { fn(); passed++; console.log(`✓ ${name}`); }
  catch (err) { failed++; console.log(`✗ ${name}\n    ${err.message}`); }
}
function expect(actual) {
  return {
    toBe(expected) {
      if (actual !== expected) throw new Error(`expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
    },
    toEqual(expected) {
      const a = JSON.stringify(actual), e = JSON.stringify(expected);
      if (a !== e) throw new Error(`expected ${e}, got ${a}`);
    },
  };
}

// --- the code under test ---
function cartReducer(cart, action) {
  switch (action.type) {
    case 'add': {
      const found = cart.find((i) => i.id === action.id);
      return found
        ? cart.map((i) => (i.id === action.id ? { ...i, qty: i.qty + 1 } : i))
        : [...cart, { id: action.id, qty: 1 }];
    }
    case 'remove':
      return cart.filter((i) => i.id !== action.id);
    default:
      return cart;
  }
}

// --- the tests ---
test('adds a new item with qty 1', () => {
  expect(cartReducer([], { type: 'add', id: 'tea' })).toEqual([{ id: 'tea', qty: 1 }]);
});
test('increments qty for an existing item', () => {
  const cart = [{ id: 'tea', qty: 1 }];
  expect(cartReducer(cart, { type: 'add', id: 'tea' })[0].qty).toBe(2);
});
test('does not mutate the original cart', () => {
  const cart = [{ id: 'tea', qty: 1 }];
  cartReducer(cart, { type: 'add', id: 'tea' });
  expect(cart[0].qty).toBe(1);
});
test('removes an item', () => {
  expect(cartReducer([{ id: 'tea', qty: 3 }], { type: 'remove', id: 'tea' })).toEqual([]);
});
test('ignores unknown actions', () => {
  const cart = [{ id: 'tea', qty: 1 }];
  expect(cartReducer(cart, { type: 'oops' })).toBe(cart);
});

console.log(`\n${passed} passed, ${failed} failed`);
✓ adds a new item with qty 1
✓ increments qty for an existing item
✓ does not mutate the original cart
✓ removes an item
✓ ignores unknown actions

5 passed, 0 failed

Testing a component

React Testing Library renders a component into a fake DOM. You then find elements the way users do — by role, label or text — and simulate interactions with user-event:

jsx
// Counter.jsx
import { useState } from 'react';
export default function Counter({ start = 0 }) {
  const [n, setN] = useState(start);
  return (
    <div>
      <p>Count: {n}</p>
      <button onClick={() => setN(n + 1)}>Increment</button>
      <button onClick={() => setN(start)} disabled={n === start}>Reset</button>
    </div>
  );
}
jsx
// Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect } from 'vitest';
import Counter from './Counter.jsx';

describe('Counter', () => {
  it('starts at the given value', () => {
    render(<Counter start={5} />);
    expect(screen.getByText('Count: 5')).toBeInTheDocument();
  });

  it('increments when the button is clicked', async () => {
    const user = userEvent.setup();
    render(<Counter />);
    await user.click(screen.getByRole('button', { name: 'Increment' }));
    await user.click(screen.getByRole('button', { name: 'Increment' }));
    expect(screen.getByText('Count: 2')).toBeInTheDocument();
  });

  it('disables Reset until the count changes', async () => {
    const user = userEvent.setup();
    render(<Counter />);
    const reset = screen.getByRole('button', { name: 'Reset' });
    expect(reset).toBeDisabled();
    await user.click(screen.getByRole('button', { name: 'Increment' }));
    expect(reset).toBeEnabled();
  });
});

Running the tests:

bash · try it yourself
npm test -- --run
 RUN  v3.2.4 /home/you/my-react-app

 ✓ src/cartReducer.test.js (5 tests) 3ms
 ✓ src/Counter.test.jsx (3 tests) 61ms

 Test Files  2 passed (2)
      Tests  8 passed (8)
   Start at  10:24:31
   Duration  1.12s (transform 64ms, setup 180ms, collect 140ms, tests 64ms, environment 410ms, prepare 120ms)

Without --run, Vitest stays in watch mode and re-runs affected tests whenever you save a file.

Queries: finding elements

Query Finds Prefer when
getByRole('button', { name: 'Save' }) by accessible role and name almost always — it also checks accessibility
getByLabelText('Email') form fields by their <label> inputs
getByText('Welcome') by visible text non-interactive content
getByTestId('chart') by data-testid last resort
Variant No match Use for
getBy… throws elements that must be there
queryBy… returns null asserting something is absent
findBy… waits (async) elements that appear later, e.g. after a fetch

Testing async UI

jsx
it('shows users after loading', async () => {
  render(<UserList fetchUsers={() => Promise.resolve([{ id: 1, name: 'Mai' }])} />);
  expect(screen.getByText(/loading/i)).toBeInTheDocument();
  expect(await screen.findByText('Mai')).toBeInTheDocument();
  expect(screen.queryByText(/loading/i)).not.toBeInTheDocument();
});

Passing the fetch function as a prop (or mocking the module with vi.mock) keeps tests fast and independent of real servers.

Tip: Test behaviour, not implementation. Don't assert on state variables or hook calls; assert on what the user sees and can do. Then you can refactor a component's internals freely, and the tests still pass.

Test yourself

Which React Testing Library query is generally preferred?

  1. getByTestId
  2. getByRole
  3. querySelector
  4. getByClassName

How do you assert that an element is NOT on the page?

  1. getByText(...) should throw
  2. expect(queryByText(...)).not.toBeInTheDocument()
  3. findByText(...)
  4. getByRole(...).hidden

Which code is easiest to unit test without rendering anything?

  1. A component with effects
  2. A pure reducer function
  3. A portal
  4. A Suspense boundary