JavaScript and React course ยท Module 13: Testing React

Main Project: Complete Test Suite - Cosmic Mission Control Center

10 min read ยท
In this lesson8

The time has come to summarize everything we've learned in this module! Commander Nova is preparing the fleet for launch, and mission control is a set of panels that must work flawlessly. Every code change can quietly break the crew form or the shield alarm, and nobody clicks through the whole app before every launch. Your task is to protect this application with a complete test suite, that is, to combine all the techniques from this module in one project.

Application Description

You will find a working version of the app in the preview at the end of the lesson. The Mission Control Center consists of the following parts:

1. MissionDashboard - Mission Panel

  • Loads the mission list through the loadMissions function it receives in props
  • Shows a loading state, an error with a retry button, and the loaded data
  • Filters missions by status
  • Displays a summary: the number of all and active missions

2. CrewManager - Crew Management

  • A form for adding crew members with the fields Name, Role and Experience (years)
  • Data validation with the validateCrewMember function (name, role, experience)
  • A list of members with remove buttons and a role filter

3. SystemStatus - Systems Status

  • Shows the ship's system levels as bars with role="progressbar"
  • Reads the sensors every 10 seconds: each reading weakens the shields by 15 points
  • Raises an alarm with role="alert" when any level drops below 30%

4. Custom Hooks

  • useMissions - loading missions, loading and error state, retry
  • useSystemHealth - reading the systems at a set interval
  • useCrewFilter - filtering the crew by role

How to Work with This Project

The preview shows the working app, but it does not run Jest. The tests in this lesson are written for exactly these components, so move the code from the preview into your own project, split it into files following the structure below and run npm test. Set the project up as in the first lesson of the module: Jest with the jsdom environment, a JSX transform and @testing-library/jest-dom in the setup file.

Tasks to Complete

Your test suite should cover all the levels you have learned in the module:

  1. Unit tests - helper functions, validation
  2. Component tests - rendering, interactions, states
  3. Async tests - data fetching, loading, errors
  4. Hook tests - custom hooks with renderHook
  5. API mocking - jest.fn() stand-ins, jest.mock, fetch mocking
  6. Snapshots - key presentational components

Test Structure

Every component, hook and helper file gets its own test file, so when a test fails you know right away where to look. Jest finds them on its own, because they live in the __tests__ folder and end with .test.js:

__tests__/
  MissionDashboard.test.js    -- mission panel tests
  CrewManager.test.js         -- crew management tests
  SystemStatus.test.js        -- system status tests
  hooks/
    useMissions.test.js       -- missions hook tests
    useCrewFilter.test.js     -- crew filter hook tests
  utils/
    validators.test.js        -- validation function tests

The __tests__ folder sits in src next to the components, and you keep the hooks and helpers in src/hooks and src/utils. Each of these files exports what you test, and the imports in the examples below assume exactly this layout.

Key Patterns to Apply

The patterns below cover the whole suite: from a pure function, through a hook and a component, to asynchrony, time and errors. Every example works with the code from the preview. The test names stay in English, as in the whole module.

Pattern: Pure Function Test

Validation does not need React: it receives an object and returns a list of errors, so you test it like the functions from the Jest lesson:

import { validateCrewMember } from '../../utils/validators';

test('rejects a one-letter name and an unknown role', () => {
  const errors = validateCrewMember({ name: 'X', role: 'cook', experience: 3 });

  expect(errors).toEqual(['Name must be at least 2 characters', 'Unknown role']);
});

toEqual compares the contents of the array, not the reference, so the test checks exactly the two messages the user will see. It is the cheapest and fastest test in the whole suite, the base of the test pyramid.

Pattern: Hook Test

You run the useCrewFilter hook with renderHook and wrap the filter change in act, as in the lesson on hooks:

import { renderHook, act } from '@testing-library/react';
import { useCrewFilter } from '../../hooks/useCrewFilter';

test('filters crew by role', () => {
  const crew = [
    { id: 1, name: 'Astro', role: 'pilot' },
    { id: 2, name: 'Commander Nova', role: 'captain' },
  ];
  const { result } = renderHook(() => useCrewFilter(crew));

  act(() => result.current.setFilter('pilot'));

  expect(result.current.filtered).toEqual([crew[0]]);
});

You read the result from result.current only after act, so you see the state after the filter change: only the pilot remains on the list. The hook knows nothing about the form or the buttons, which is why its test is short and resistant to changes in the look of the app.

Pattern: Arrange-Act-Assert

Every component test has three parts. First you prepare the scene (Arrange), then you perform an action like a user (Act), and finally you check the result (Assert). The comments in the test show this split:

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

test('adds new crew member', async () => {
  // Arrange: prepare
  const user = userEvent.setup();
  render(<CrewManager />);

  // Act: execute
  await user.type(screen.getByLabelText('Name'), 'Ra');
  await user.selectOptions(screen.getByLabelText('Role'), 'captain');
  await user.click(screen.getByRole('button', { name: 'Add crew member' }));

  // Assert: verify
  expect(screen.getByText('Ra (captain, 0 years)')).toBeInTheDocument();
});

getByLabelText finds the fields because the labels are linked to them with htmlFor and id. The assertion looks for the whole list entry, not just the word "captain", because that word is also an option in the select, and the test would pass even if adding did not work. Add a second test for the error path: the name X should show a message in an element with role="alert".

Pattern: Test Isolation

Tests in one file must not depend on each other. A stand-in shared by several tests remembers the calls from the previous ones, so without cleanup the count from the first test would break the assertion in the second. That is why beforeEach clears the history before every test:

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

const missions = [{ id: 1, name: 'Apollo 11', status: 'completed', crew: 3 }];
const loadMissions = jest.fn();

beforeEach(() => {
  // Every test starts with an empty mock call history
  jest.clearAllMocks();
});

test('shows missions after loading', async () => {
  loadMissions.mockResolvedValue(missions);
  render(<MissionDashboard loadMissions={loadMissions} />);

  expect(screen.getByRole('status')).toHaveTextContent('Loading missions...');
  expect(await screen.findByText('Apollo 11')).toBeInTheDocument();
  expect(loadMissions).toHaveBeenCalledTimes(1);
});

The panel receives the loadMissions function in props, so in the test you pass a jest.fn() stand-in instead of the real API, and in the preview the same prop gets a simulated server. First you see the loading state with role="status", and findByText waits until the data appears. The second test checks the error path and the retry:

test('shows an error and retries', async () => {
  const user = userEvent.setup();
  loadMissions
    .mockRejectedValueOnce(new Error('No connection to the mission server'))
    .mockResolvedValueOnce(missions);
  render(<MissionDashboard loadMissions={loadMissions} />);

  expect(await screen.findByRole('alert')).toHaveTextContent('No connection');
  await user.click(screen.getByRole('button', { name: 'Try again' }));

  expect(await screen.findByText('Apollo 11')).toBeInTheDocument();
  expect(loadMissions).toHaveBeenCalledTimes(2);
});

The two Once calls set up consecutive responses: first a failure, then data. Without jest.clearAllMocks() in beforeEach, this test would also count the call from the previous test and see 3 instead of 2. When a component calls fetch itself, also add global.fetch = jest.fn() to beforeEach, as in the lesson on mocking.

Pattern: Time Under Control

The shield alarm appears only after two sensor readings, that is, after 20 seconds. Fake timers fast-forward this time in a fraction of a second:

import { act } from 'react';
import { render, screen } from '@testing-library/react';
import SystemStatus from '../SystemStatus';

test('raises an alert when shields drop below 30%', () => {
  jest.useFakeTimers();
  render(<SystemStatus />);
  expect(screen.queryByRole('alert')).not.toBeInTheDocument();

  // Two sensor readings: 55% -> 40% -> 25%
  act(() => {
    jest.advanceTimersByTime(20000);
  });

  expect(screen.getByRole('progressbar', { name: 'Shields' })).toHaveAttribute('aria-valuenow', '25');
  expect(screen.getByRole('alert')).toHaveTextContent('Shields');
  jest.useRealTimers();
});

queryByRole at the start confirms that there is no alarm yet, because getByRole would throw an error at that point. Moving the clock changes state outside RTL's tools, which is why it sits inside act. You find the bar by the progressbar role and the name from aria-label, and you read its value from aria-valuenow.

Pattern: Error Boundary Testing

An Error Boundary is a component that catches an error thrown while its children render and shows a fallback message instead of a blank screen. React has no hook for this, so you write the boundary as a class component with a static getDerivedStateFromError method, or you take a ready one from the react-error-boundary library:

import { Component } from 'react';

class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  render() {
    return this.state.hasError ? this.props.fallback : this.props.children;
  }
}

getDerivedStateFromError sets hasError, and render then shows the element from the fallback prop. The test hands the boundary a component that always throws:

test('shows error boundary on crash', () => {
  const ThrowError = () => {
    throw new Error('Kaboom!');
  };

  // React 19 reports an error caught by a boundary with console.error
  const spy = jest.spyOn(console, 'error').mockImplementation(() => {});

  render(
    <ErrorBoundary fallback={<p>Something went wrong</p>}>
      <ThrowError />
    </ErrorBoundary>
  );

  expect(screen.getByText('Something went wrong')).toBeInTheDocument();
  spy.mockRestore();
});

In React 19 an error caught by a boundary goes to console.error, so without the spy the test passes but clutters the output with a red stack trace. mockRestore() at the end gives the console its real function back, so that later tests see warnings again.

Testing Best Practices

  1. Test behavior, not implementation - check what the user sees
  2. One concept per test - each test checks one thing
  3. Readable test names - it('displays error when mission not found')
  4. DRY in tests with moderation - duplication in tests is better than overly complicated abstractions
  5. Test success and error paths - the happy path and edge cases
  6. Don't test the framework - don't test whether useState works, test your logic

What You Hand In to Your Mentor

After this lesson a mentor project awaits you. Build your own React app or extend the Mission Control Center, and prepare a test suite for it that covers:

  • a panel with data from an API (a stand-in instead of the real server in tests), with loading and error handling
  • a form with validation, checked with userEvent and messages with role="alert"
  • at least one custom hook tested with renderHook
  • unit tests, integration tests of several components and a snapshot of a simple presentational component
  • success paths and edge cases

Push the project with its tests to GitHub and send the repository link. Your mentor will run npm test, so make sure all tests pass on a fresh copy of the project.

Check the Preview

Below you will find the working Mission Control Center. Click through it and compare it with the tests from the lesson:

  • click Simulate a server failure: the panel shows an error and a Try again button, just like in the error path test, and after you click Restore the server it loads the missions again
  • add a crew member with a one-letter name and see the validation messages
  • wait 20 seconds until the shields drop below 30% and the alarm appears

My advice: before you write a test, click through the scenario in the preview and write it down as three steps: Arrange, Act and Assert. Then the test almost writes itself. Remember: a good test suite is a pre-launch check that inspects the whole ship on every code change before you fly into real space.

Code for this lesson: App.jsx
import React, { useState, useEffect, useCallback } from 'react';

// ===== Simulated API =====
// The preview has no server, so a Promise with setTimeout fakes the response.
// In the lesson's tests MissionDashboard gets a jest.fn() mock instead.
const MISSIONS = [
  { id: 1, name: 'Apollo 11', status: 'completed', crew: 3 },
  { id: 2, name: 'Artemis II', status: 'active', crew: 4 },
  { id: 3, name: 'Europa Clipper', status: 'active', crew: 0 },
  { id: 4, name: 'Mars Sample Return', status: 'planned', crew: 0 },
];

function fetchMissions(serverDown) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (serverDown) reject(new Error('No connection to the mission server'));
      else resolve(MISSIONS);
    }, 800);
  });
}

// ===== Helper functions =====
const ROLES = { captain: 'captain', pilot: 'pilot', engineer: 'engineer', scientist: 'scientist' };
const FILTER_LABELS = { all: 'all', active: 'active', completed: 'completed', planned: 'planned' };
const STATUS_LABELS = { active: 'active', completed: 'completed', planned: 'planned' };
const SYSTEM_LABELS = { engine: 'Engine', shields: 'Shields', navigation: 'Navigation', lifeSupport: 'Life support' };

function validateCrewMember(member) {
  const errors = [];
  if (!member.name || member.name.trim().length < 2) {
    errors.push('Name must be at least 2 characters');
  }
  if (!Object.keys(ROLES).includes(member.role)) {
    errors.push('Unknown role');
  }
  if (member.experience < 0 || member.experience > 50) {
    errors.push('Experience must be between 0 and 50 years');
  }
  return errors;
}

function yearsLabel(n) {
  return n === 1 ? '1 year' : `${n} years`;
}

// ===== Custom hooks =====
function useMissions(loadMissions) {
  const [missions, setMissions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [attempt, setAttempt] = useState(0);

  useEffect(() => {
    let ignore = false;
    loadMissions()
      .then(data => {
        if (!ignore) setMissions(data);
      })
      .catch(err => {
        if (!ignore) setError(err.message);
      })
      .finally(() => {
        if (!ignore) setLoading(false);
      });
    return () => {
      ignore = true;
    };
  }, [loadMissions, attempt]);

  // Retry: show the loading state at once and fetch again
  const refetch = useCallback(() => {
    setLoading(true);
    setError(null);
    setAttempt(a => a + 1);
  }, []);
  return { missions, loading, error, refetch };
}

function useCrewFilter(crew) {
  const [filter, setFilter] = useState('all');
  const filtered = filter === 'all' ? crew : crew.filter(member => member.role === filter);
  return { filtered, filter, setFilter };
}

function useSystemHealth(intervalMs = 10000) {
  const [systems, setSystems] = useState({ engine: 98, shields: 55, navigation: 100, lifeSupport: 92 });

  useEffect(() => {
    // Every sensor reading weakens the shields by 15 points
    const id = setInterval(() => {
      setSystems(s => ({ ...s, shields: Math.max(s.shields - 15, 0) }));
    }, intervalMs);
    return () => clearInterval(id);
  }, [intervalMs]);

  const repairShields = () => setSystems(s => ({ ...s, shields: 100 }));
  return { systems, repairShields };
}

// ===== Components =====
function MissionDashboard({ loadMissions }) {
  const { missions, loading, error, refetch } = useMissions(loadMissions);
  const [statusFilter, setStatusFilter] = useState('all');

  if (loading) {
    return (
      <section className="panel">
        <h2>Mission dashboard</h2>
        <p className="loading" role="status">Loading missions...</p>
      </section>
    );
  }

  if (error) {
    return (
      <section className="panel">
        <h2>Mission dashboard</h2>
        <p className="error" role="alert">Error: {error}</p>
        <button className="refresh-btn" onClick={refetch}>Try again</button>
      </section>
    );
  }

  const visible = statusFilter === 'all' ? missions : missions.filter(m => m.status === statusFilter);

  return (
    <section className="panel">
      <h2>Mission dashboard</h2>
      <div className="stats">
        <div className="stat">Total: {missions.length}</div>
        <div className="stat">Active: {missions.filter(m => m.status === 'active').length}</div>
      </div>

      <div className="filters">
        {Object.keys(FILTER_LABELS).map(s => (
          <button key={s} aria-pressed={statusFilter === s} onClick={() => setStatusFilter(s)}>
            {FILTER_LABELS[s]}
          </button>
        ))}
      </div>

      <ul className="mission-list" aria-label="Missions">
        {visible.map(m => (
          <li key={m.id}>
            <strong>{m.name}</strong>
            <span className="badge">{STATUS_LABELS[m.status]}</span>
            <span className="crew-count">crew: {m.crew}</span>
          </li>
        ))}
      </ul>

      <button className="refresh-btn" onClick={refetch}>Refresh</button>
    </section>
  );
}

function CrewManager() {
  const [crew, setCrew] = useState([
    { id: 1, name: 'Commander Nova', role: 'captain', experience: 15 },
    { id: 2, name: 'Astro', role: 'pilot', experience: 6 },
    { id: 3, name: 'Engineer Bolt', role: 'engineer', experience: 8 },
  ]);
  const [formData, setFormData] = useState({ name: '', role: 'pilot', experience: 0 });
  const [errors, setErrors] = useState([]);
  const { filtered, filter, setFilter } = useCrewFilter(crew);

  const handleSubmit = (e) => {
    e.preventDefault();
    const validationErrors = validateCrewMember(formData);
    if (validationErrors.length > 0) {
      setErrors(validationErrors);
      return;
    }
    setCrew(prev => [...prev, { ...formData, name: formData.name.trim(), id: Date.now() }]);
    setFormData({ name: '', role: 'pilot', experience: 0 });
    setErrors([]);
  };

  const handleRemove = (id) => {
    setCrew(prev => prev.filter(m => m.id !== id));
  };

  return (
    <section className="panel">
      <h2>Crew manager</h2>

      <form className="crew-form" onSubmit={handleSubmit}>
        <div className="field">
          <label htmlFor="crew-name">Name</label>
          <input
            id="crew-name"
            value={formData.name}
            onChange={e => setFormData(d => ({ ...d, name: e.target.value }))}
          />
        </div>
        <div className="field">
          <label htmlFor="crew-role">Role</label>
          <select
            id="crew-role"
            value={formData.role}
            onChange={e => setFormData(d => ({ ...d, role: e.target.value }))}
          >
            {Object.entries(ROLES).map(([value, label]) => (
              <option key={value} value={value}>{label}</option>
            ))}
          </select>
        </div>
        <div className="field">
          <label htmlFor="crew-exp">Experience (years)</label>
          <input
            id="crew-exp"
            type="number"
            value={formData.experience}
            onChange={e => setFormData(d => ({ ...d, experience: Number(e.target.value) }))}
          />
        </div>
        <button type="submit">Add crew member</button>
      </form>

      {errors.length > 0 && (
        <div className="error-list" role="alert">
          {errors.map(message => <p key={message}>{message}</p>)}
        </div>
      )}

      <div className="filters">
        {['all', ...Object.keys(ROLES)].map(r => (
          <button key={r} aria-pressed={filter === r} onClick={() => setFilter(r)}>
            {r === 'all' ? 'everyone' : ROLES[r]}
          </button>
        ))}
      </div>

      <ul className="crew-list" aria-label="Crew">
        {filtered.map(m => (
          <li key={m.id}>
            <span>{m.name} ({ROLES[m.role]}, {yearsLabel(m.experience)})</span>
            <button className="remove" aria-label={`Remove: ${m.name}`} onClick={() => handleRemove(m.id)}>
              Remove
            </button>
          </li>
        ))}
      </ul>
    </section>
  );
}

function SystemStatus() {
  const { systems, repairShields } = useSystemHealth(10000);
  const critical = Object.keys(systems).filter(key => systems[key] < 30);

  const getStatusColor = (level) => {
    if (level > 80) return '#4caf50';
    if (level > 50) return '#ff9800';
    return '#f44336';
  };

  return (
    <section className="panel">
      <h2>System status</h2>
      <p className="hint">Sensor reading every 10 s: the shields weaken by 15 points.</p>
      <div className="system-grid">
        {Object.entries(systems).map(([key, value]) => (
          <div key={key} className="system-item">
            <span className="system-name">{SYSTEM_LABELS[key]}</span>
            <div
              className="progress-bar"
              role="progressbar"
              aria-label={SYSTEM_LABELS[key]}
              aria-valuenow={value}
              aria-valuemin={0}
              aria-valuemax={100}
            >
              <div className="progress-fill" style={{ width: `${value}%`, background: getStatusColor(value) }} />
            </div>
            <span className="system-value">{value}%</span>
          </div>
        ))}
      </div>
      {critical.length > 0 && (
        <div className="system-alert">
          <p role="alert">Critical level: {critical.map(key => SYSTEM_LABELS[key]).join(', ')}</p>
          <button onClick={repairShields}>Repair shields</button>
        </div>
      )}
    </section>
  );
}

export default function App() {
  const [serverDown, setServerDown] = useState(false);
  const loadMissions = useCallback(() => fetchMissions(serverDown), [serverDown]);

  return (
    <div className="app">
      <h1>Cosmic Mission Control Center</h1>
      <p className="subtitle">
        Main project: a working app that the lesson's tests check.
        The preview does not run Jest, you run the tests in your own project.
      </p>
      <button className="sim-btn" onClick={() => setServerDown(d => !d)} aria-pressed={serverDown}>
        {serverDown ? 'Restore the server' : 'Simulate a server failure'}
      </button>
      {/* key: after the server switch the panel starts over from the loading state */}
      <MissionDashboard key={serverDown ? 'down' : 'up'} loadMissions={loadMissions} />
      <CrewManager />
      <SystemStatus />
    </div>
  );
}

Docs entries used in this lesson

Spotted a mistake in this lesson?

  1. Project to submitMentor Project: Test suite for space application
  2. VideoModule Summary

Useful articles