Skip to main content
XenonStack

DevOps

XenonStack Blog TDD with React and Jest: A Practical Guide

| Published | Updated

Key takeaway

  • Test driven development with React and Jest: the red, green, refactor cycle, Jest setup, snapshot tests, React Testing Library and why Enzyme is now dated.

Test driven development (TDD) is a way of building software in which you write a failing test first, write just enough code to pass it, and then clean up the design. In a React project, Jest is the usual test runner for that loop, often paired with React Testing Library.

This guide is for front-end developers, tech leads and QA engineers who want a working TDD routine for React components. It covers the cycle, a minimal Jest setup, snapshot tests, which tools to choose today, and where AI agents fit. It extends our guides to test driven development tools and the agile process and AI in software testing.

What is test driven development?

Martin Fowler describes TDD on his bliki as a repeated loop, often summarised as red, green, refactor. You write a test for the next bit of functionality, write the functional code until the test passes, and then refactor both the new and the old code so that it is well structured. He also notes that the most common way to get TDD wrong is neglecting the third step.

Each cycle is small, so a feature grows as a series of tested steps. The same idea sits behind unit testing in other stacks: see our guides to test driven development in Python and test-driven database development.

How does the red, green, refactor cycle work in React?

Take a component that shows a notification menu. The cycle looks like this:

Two-column diagram. Write and pass: pick behaviour, red, green, run Jest. Clean and repeat: refactor, re-run tests, review snapshots, repeat.
  1. Red. Write a test that renders the component and expects the menu to open when a user clicks the bell. It fails because the component does not exist yet.
  2. Green. Write the smallest component that makes the test pass, even if it is plain.
  3. Refactor. Remove duplication, rename things and improve the structure, re-running the tests after every change.
  4. Repeat with the next behaviour, such as closing the menu or showing a count.

How do you set up Jest for a React project?

The Jest getting started guide says to install Jest with your package manager, for example with npm, and shows a first test that uses test to define the case, expect to wrap the value and toBe to check it. Add a test script to package.json and run it with npm test. Jest works with Babel through babel-jest, which transforms files automatically when a Babel configuration exists, and TypeScript can be supported through Babel or ts-jest. Note that the Babel route transpiles only and does not type-check your tests.

npm install --save-dev jest

// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

For React components you also need an environment that can render them and a library to query the result. The next sections cover the options.

What is snapshot testing, and when should you use it?

The Jest snapshot testing docs explain that snapshot tests are useful when you want to make sure your UI does not change unexpectedly. A test renders a component, takes a snapshot and compares it with a reference file stored beside the test. If the two differ, either the change is unexpected or the reference needs updating.

Treat snapshots as code. The docs say to commit them and review them in your regular code review, to keep them focused and short, and to make sure they hold no non-deterministic data such as the current time. They also warn against regenerating snapshots just to silence a failing suite: find the cause first, and fix bugs before running the update command so you do not record buggy behaviour.

Which React testing tools should you use now?

Many older tutorials build around Enzyme. That advice is dated. In December 2021 the maintainer of an unofficial React 17 adapter wrote that Enzyme is dead: the official React 17 adapter was never merged, and he concluded that a React 18 adapter was not feasible without a major rework. He recommends React Testing Library for new tests.

ToolRoleCurrent status from the sources read
JestTest runner and assertionsDocumented install, Babel and TypeScript routes; supports snapshot tests
React Testing LibraryRenders components and queries the DOMDescribed by its docs as a very light-weight solution that builds on DOM Testing Library; works with any test framework, Jest recommended
EnzymeComponent utilities for shallow and full renderingMaintainer of a React 17 adapter says it is dead and that a React 18 adapter is not feasible

The React Testing Library docs state the guiding principle that the more your tests resemble the way your software is used, the more confidence they can give you. They advise avoiding implementation details so that a refactor that keeps behaviour does not break tests, which fits the third step of TDD well. The library is described as a replacement for Enzyme, which offers utilities that make testing implementation details easy.

How do TDD and acceptance test driven development differ?

Acceptance test driven development (ATDD) starts one level higher: the user, the business owner and the developer agree what a story must do, and acceptance tests are written before coding starts. The two work together, and our guide to software testing automation trends and the page on system testing types and tools show where each level fits.

Test levelQuestion it answersTypical React example
UnitIs this piece built right?A reducer returns the right state for an action
IntegrationDo several units work together?A form component and its validation hook
SystemDoes the whole product work?A full checkout flow in a browser
AcceptanceDid we build the right thing?A user story signed off against its criteria

How do AI agents change test driven development?

AI coding agents can write a component quickly, which makes the failing test more valuable, not less: it states what the agent must achieve and stops a change that breaks agreed behaviour. Write the tests yourself or review them closely, then let an agent iterate until they pass. XenonStack's ElixirClaw is the AI agents computing platform for building and running such workflows. For data-heavy interfaces, see our work on big data services, machine learning and reactive programming.

What should you do first?

  1. Pick one small component and write its first failing test.
  2. Install Jest and run the test with npm test.
  3. Add React Testing Library and query by what the user sees.
  4. Review any snapshots in code review and keep them short.
  5. Plan the move off Enzyme before you upgrade React.

To map one decision your agents make, and the data and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What is test driven development?

It is a loop of writing a failing test, writing the code that makes it pass, and refactoring, often called red, green, refactor.

Is Jest enough to test a React app?

Jest runs tests and assertions. React Testing Library, which works with any test framework and recommends Jest, renders components and queries the output.

Should I still use Enzyme?

For new work, the maintainer of an unofficial React 17 adapter recommends React Testing Library, and says a React 18 adapter is not feasible.

When should I use snapshot tests?

Use them when you want to be told if rendered output changes unexpectedly, and review every changed snapshot in code review.

What is the difference between TDD and ATDD?

TDD drives code design from small unit tests. ATDD writes acceptance tests with the business owner before development of a story starts.

Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.

Ready to put AI agents to work? Explore ElixirClaw, the agentic OS platform to build, orchestrate and govern AI agents.

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in solving your challenges with the XenonStack team?
Get Started

Tell us about you and your priorities so we can prepare the right conversation. It takes about 2 minutes.

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Continue