Skip to content

TDD Kata: FizzBuzz and Beyond

Medium ~40 min

What you'll build

A FizzBuzz implementation and a Roman numeral converter, both built strictly with TDD — red, green, refactor cycle.

Goals

  • Follow the red-green-refactor cycle
  • Write the smallest failing test first
  • Implement minimal code to pass
  • Refactor with confidence under test coverage

Prerequisites

  • Basic test syntax
  • Writing functions
  • Understanding of TDD concepts

Steps

  1. 1

    TDD FizzBuzz: write the first test

    Start with the simplest test: fizzbuzz(1) should return '1'. Write only this test, run it, and see it fail (red). Then write the minimal implementation to pass (green).

    Code
    // test/fizzbuzz.test.ts
    import { fizzbuzz } from '../fizzbuzz';
    
    describe('fizzbuzz', () => {
      it('returns the number as string for 1', () => {
        expect(fizzbuzz(1)).toBe('1');
      });
    });
    
    // src/fizzbuzz.ts — minimal implementation
    export function fizzbuzz(n: number): string {
      return '1';
    }

    Expected result

    Test passes. The implementation is deliberately minimal — TDD drives design incrementally.

  2. 2

    Add tests for 2 and 3

    Add a test for fizzbuzz(2) === '2'. Watch it fail, then generalize the implementation. Then add fizzbuzz(3) === 'Fizz' — this drives the Fizz logic.

  3. 3

    Add tests for 5 and 15

    Add tests for fizzbuzz(5) === 'Buzz' and fizzbuzz(15) === 'FizzBuzz'. Each test drives new logic. Follow red-green-refactor for each.

  4. 4

    Refactor the implementation

    Now that all tests pass, refactor the code for clarity without changing behavior. The tests protect you during refactoring.

    Code
    export function fizzbuzz(n: number): string {
      let result = '';
      if (n % 3 === 0) result += 'Fizz';
      if (n % 5 === 0) result += 'Buzz';
      return result || String(n);
    }

    Expected result

    All tests still pass after refactoring — the cleaner implementation is verified safe.

  5. 5

    TDD Roman numerals: start the kata

    Begin a new TDD kata: convert integers to Roman numerals. Start with the simplest test: toRoman(1) === 'I'. Build up incrementally: 5 → 'V', 10 → 'X', 4 → 'IV', 9 → 'IX'.

Try it yourself

What you learned

You practiced TDD through katas — the red-green-refactor cycle. Writing tests first drives simpler, more testable designs, and the growing test suite gives you confidence to refactor.

Related Resources

Related Lessons

  • TDD

    Test-Driven Development.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic