September 5, 2026

Simple Example of Test-Driven Development(TDD) in JavaScript – Step by Step Tutorial

Updated August 2026 — full tutorial restored for this URL.

Test-Driven Development (TDD) means write a failing test first, make it pass with the simplest code, then refactor. Here is a tiny JavaScript kata with Jest.

C# twin: TDD in Visual Studio C#.

  1. Setup Jest
  2. Red – failing test
  3. Green – minimal code
  4. Refactor
  5. Add the next requirement

1. Setup Jest

npm init -y
npm i -D jest
# package.json → "test": "jest"

Kata: sum(numbers: string): number — empty string → 0; comma-separated integers sum.

2. Red – failing test

// sum.test.js
const { sum } = require("./sum");

test("empty string is 0", () => {
  expect(sum("")).toBe(0);
});
npm test   # fails — module missing

3. Green – minimal code

// sum.js
function sum(numbers) {
  if (numbers === "") return 0;
  return 0; // still enough for this one test
}
module.exports = { sum };

4. Refactor

Nothing much yet — keep tests green. Add the next test before inventing features.

5. Add the next requirement

test("sums comma-separated numbers", () => {
  expect(sum("1,2,3")).toBe(6);
});
function sum(numbers) {
  if (numbers === "") return 0;
  return numbers.split(",").map(Number).reduce((a, b) => a + b, 0);
}

Rhythm: red → green → refactor. Never pile features without a failing test that demands them.

Kindson Munonye

Kindson Munonye is a software engineer and technical author covering machine learning, statistics, REST APIs, Python, and software engineering. He publishes free tutorials on The Genius Blog and live classes on Alkademy. GitHub · LinkedIn · About · Alkademy

View all posts by Kindson Munonye →
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted