Skip to content
TDD — Explained with Examples

TDD — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

TDD (Test-Driven Development) is a software development process where you write tests before code, following the Red-Green-Refactor cycle.

TDD stands for Test-Driven Development, popularized by Kent Beck in the late 1990s as part of Extreme Programming. The mantra is “Red, Green, Refactor.”

The TDD Cycle

  1. Red — Write a failing test that defines the desired behavior
  2. Green — Write the minimum code to make the test pass
  3. Refactor — Clean up the code while keeping tests passing
[RED]   Write failing test   →  Test fails (expected)
[GREEN] Write minimal code   →  Test passes
[REFACTOR] Improve code      →  Test still passes (safety net)

TDD in Action

// Step 1: RED — write a test first
describe('FizzBuzz', () => {
  test('returns "Fizz" for multiples of 3', () => {
    expect(fizzBuzz(3)).toBe('Fizz');
  });
});
// Test fails: fizzBuzz is not defined

// Step 2: GREEN — write minimum code
function fizzBuzz(n) {
  return 'Fizz';
}
// Test passes!

// Step 3: RED — add another test
test('returns "Buzz" for multiples of 5', () => {
  expect(fizzBuzz(5)).toBe('Buzz');
});
// Test fails

// Step 4: GREEN
function fizzBuzz(n) {
  if (n % 3 === 0) return 'Fizz';
  return 'Buzz';
}
// All tests pass

// Step 5: RED — edge case
test('returns "FizzBuzz" for multiples of 3 and 5', () => {
  expect(fizzBuzz(15)).toBe('FizzBuzz');
});
// Test fails

// Step 6: GREEN + REFACTOR
function fizzBuzz(n) {
  if (n % 15 === 0) return 'FizzBuzz';
  if (n % 3 === 0) return 'Fizz';
  if (n % 5 === 0) return 'Buzz';
  return String(n);
}
// All tests pass — clean solution

Real-World Analogy

TDD is like sketching the blueprint for a house before building it. You don’t start hammering nails randomly. You write the requirements down (tests), then build exactly to those specifications. When you want to add a window (new feature), you first mark where it goes on the blueprint (write test), then cut the hole (write code). The blueprint always tells you if the house matches the plan.

Benefits of TDD

  • Design feedback — writing tests first forces you to think about API design
  • Regression safety net — every feature has a test that catches regressions
  • Debugging reduction — you know the most recent change broke things
  • Living documentation — tests describe what the code should do

Related Terms

Unit Testing, BDD, Mock vs Stub, Refactoring, CI/CD

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro