JavaScript and TypeScript course ยท Module 10: TypeScript in Practice

Test-Driven Development (TDD) - Code Evolution Through Tests

9 min read ยท
In this lesson6

Welcome to the world of Test-Driven Development! Imagine changing a single line in the fence system without knowing whether you have just switched off the alarm on the Velociraptor paddock. Just as the scientists in Jurassic Park first had to understand dinosaur DNA before they could clone it, TDD requires you to define the expected behavior (the test) first, and only then write the implementation.

What is TDD?

Test-Driven Development is a programming technique in which we first write a test that initially fails, then the minimal code needed to pass it, and finally we refactor the code while keeping the tests passing. The technique was popularized by Kent Beck around the turn of the 21st century.

The Red-Green-Refactor Cycle

This rhythm repeats over and over, and each turn should be short, ideally a few minutes:

    +--------------------------------------+
    |                                      |
    |   RED                                |
    |   Write a test that fails            |
    |                                      |
    +---------------+----------------------+
                    |
                    v
    +--------------------------------------+
    |                                      |
    |   GREEN                              |
    |   Write minimal code to              |
    |   pass the test                      |
    |                                      |
    +---------------+----------------------+
                    |
                    v
    +--------------------------------------+
    |                                      |
    |   REFACTOR                           |
    |   Improve code while keeping         |
    |   tests passing                      |
    |                                      |
    +---------------+----------------------+
                    |
                    +----------> Repeat the cycle

A red test proves that the test can detect anything at all. Green means the requirement is met, and refactoring improves the code without changing its behavior.

TDD in Practice - Jurassic Park Example

Imagine that you are building a dinosaur monitoring system. We start with a test.

Step 1: RED - Write the Test

A test in Vitest describes behavior in describe and it blocks, and the comments show the AAA pattern: Arrange, Act, Assert:

// dinosaur.test.js
import { describe, it, expect } from 'vitest';
import { Dinosaur } from './dinosaur';

describe('Dinosaur', () => {
  describe('constructor', () => {
    it('should create a dinosaur with name and species', () => {
      // Arrange & Act
      const dino = new Dinosaur('Rex', 'Tyrannosaurus');

      // Assert
      expect(dino.name).toBe('Rex');
      expect(dino.species).toBe('Tyrannosaurus');
    });
  });

  describe('isDangerous', () => {
    it('should return true for carnivore dinosaurs', () => {
      const dino = new Dinosaur('Rex', 'Tyrannosaurus', 'carnivore');
      expect(dino.isDangerous()).toBe(true);
    });

    it('should return false for herbivore dinosaurs', () => {
      const dino = new Dinosaur('Steggy', 'Stegosaurus', 'herbivore');
      expect(dino.isDangerous()).toBe(false);
    });
  });
});

This test fails right now, and that is good, because we do not have a Dinosaur class yet, so the report shows red.

Step 2: GREEN - Minimal Code

We write the simplest code that satisfies the tests, with nothing added for the future:

// dinosaur.js
export class Dinosaur {
  constructor(name, species, diet = 'unknown') {
    this.name = name;
    this.species = species;
    this.diet = diet;
  }

  isDangerous() {
    return this.diet === 'carnivore';
  }
}

Now the tests pass. The code looks modest, but it does exactly what the tests describe and nothing more.

Step 3: REFACTOR - Improve the Code

With a green safety net in place, we tidy up the code: private # fields, getters and a constant with the list of dangerous diets:

// dinosaur.js - after refactoring
const DANGEROUS_DIETS = ['carnivore', 'omnivore'];

export class Dinosaur {
  #name;
  #species;
  #diet;

  constructor(name, species, diet = 'unknown') {
    this.#validateInput(name, species);
    this.#name = name;
    this.#species = species;
    this.#diet = diet;
  }

  get name() { return this.#name; }
  get species() { return this.#species; }
  get diet() { return this.#diet; }

  #validateInput(name, species) {
    if (!name || !species) {
      throw new Error('Name and species are required');
    }
  }

  isDangerous() {
    return DANGEROUS_DIETS.includes(this.#diet);
  }
}

Note: this is not a pure refactoring. This version treats omnivores as dangerous and throws an error when the name is missing, which means it changes the behavior. In real TDD each of these rules starts with a new, red test, and refactoring changes only the structure of the code.

Advanced TDD - Park Security System

Now we will build a more complex system, starting with a full set of tests.

Test Suite for SecuritySystem

beforeEach creates a fresh system before every test, so the tests do not affect each other, and vi.fn() creates a spy function that records its calls:

// security-system.test.js
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { SecuritySystem } from './security-system';
import { Enclosure } from './enclosure';
import { Dinosaur } from './dinosaur';

describe('SecuritySystem', () => {
  let securitySystem;
  let mockEnclosure;
  let mockDinosaur;

  beforeEach(() => {
    mockDinosaur = new Dinosaur('Rex', 'Tyrannosaurus', 'carnivore');
    mockEnclosure = new Enclosure('Paddock 1', [mockDinosaur], {
      fenceVoltage: 10000,
      isActive: true
    });
    securitySystem = new SecuritySystem();
    securitySystem.addEnclosure(mockEnclosure);
  });

  describe('addEnclosure', () => {
    it('should add an enclosure to monitoring', () => {
      const newEnclosure = new Enclosure('Paddock 2', [], { fenceVoltage: 5000 });
      securitySystem.addEnclosure(newEnclosure);

      expect(securitySystem.getEnclosures()).toHaveLength(2);
    });

    it('should throw error for duplicate enclosure names', () => {
      const duplicate = new Enclosure('Paddock 1', [], { fenceVoltage: 5000 });

      expect(() => securitySystem.addEnclosure(duplicate))
        .toThrow('Enclosure with this name already exists');
    });
  });

  describe('checkStatus', () => {
    it('should return SAFE when all fences are active', () => {
      expect(securitySystem.checkStatus()).toBe('SAFE');
    });

    it('should return DANGER when any fence is inactive', () => {
      mockEnclosure.deactivateFence();

      expect(securitySystem.checkStatus()).toBe('DANGER');
    });

    it('should return CRITICAL when dangerous dino escapes', () => {
      mockEnclosure.deactivateFence();
      mockEnclosure.markEscaped(mockDinosaur);

      expect(securitySystem.checkStatus()).toBe('CRITICAL');
    });
  });

  describe('getAlerts', () => {
    it('should return empty array when everything is safe', () => {
      expect(securitySystem.getAlerts()).toEqual([]);
    });

    it('should generate alert when fence voltage drops', () => {
      mockEnclosure.setFenceVoltage(1000);

      const alerts = securitySystem.getAlerts();

      expect(alerts).toHaveLength(1);
      expect(alerts[0]).toMatchObject({
        type: 'LOW_VOLTAGE',
        enclosure: 'Paddock 1',
        severity: 'WARNING'
      });
    });
  });

  describe('emergencyProtocol', () => {
    it('should trigger alarms for all affected zones', async () => {
      const alarmSpy = vi.fn();
      securitySystem.onAlarm(alarmSpy);

      await securitySystem.emergencyProtocol('Paddock 1');

      expect(alarmSpy).toHaveBeenCalledWith({
        type: 'EMERGENCY',
        enclosure: 'Paddock 1',
        actions: ['LOCKDOWN', 'EVACUATE', 'ALERT_SECURITY']
      });
    });
  });
});

The tests speak the language of the park: a duplicate paddock is an error, a disabled fence means DANGER, and an escaped predator means CRITICAL.

Implementation After TDD

The implementation grows test by test until all of them turn green:

// security-system.js
export class SecuritySystem {
  #enclosures = new Map();
  #alarmCallbacks = [];

  addEnclosure(enclosure) {
    if (this.#enclosures.has(enclosure.name)) {
      throw new Error('Enclosure with this name already exists');
    }
    this.#enclosures.set(enclosure.name, enclosure);
  }

  getEnclosures() {
    return Array.from(this.#enclosures.values());
  }

  checkStatus() {
    const enclosures = this.getEnclosures();

    for (const enclosure of enclosures) {
      const escaped = enclosure.getEscapedDinosaurs();
      if (escaped.some(dino => dino.isDangerous())) {
        return 'CRITICAL';
      }
    }

    for (const enclosure of enclosures) {
      if (!enclosure.isFenceActive()) {
        return 'DANGER';
      }
    }

    return 'SAFE';
  }

  getAlerts() {
    const alerts = [];
    const MINIMUM_SAFE_VOLTAGE = 5000;

    for (const enclosure of this.getEnclosures()) {
      if (enclosure.getFenceVoltage() < MINIMUM_SAFE_VOLTAGE) {
        alerts.push({
          type: 'LOW_VOLTAGE',
          enclosure: enclosure.name,
          severity: 'WARNING',
          currentVoltage: enclosure.getFenceVoltage()
        });
      }
    }

    return alerts;
  }

  onAlarm(callback) {
    this.#alarmCallbacks.push(callback);
  }

  async emergencyProtocol(enclosureName) {
    const alarmData = {
      type: 'EMERGENCY',
      enclosure: enclosureName,
      actions: ['LOCKDOWN', 'EVACUATE', 'ALERT_SECURITY']
    };

    for (const callback of this.#alarmCallbacks) {
      await callback(alarmData);
    }
  }
}

The order in checkStatus is not accidental: first the escape, then the fences, because the CRITICAL test disables the fence and marks the escape at the same time. The Enclosure class is not shown here, but its interface follows directly from the tests.

Benefits of TDD

Confidence in Changes

The most important benefit is a safety net for every change:

// With TDD you have a safety net: if tests pass, the tested behaviors still work

Tests protect only what they check. A green result does not prove the absence of bugs, but it tells you that the described behaviors still work.

Documentation in Code

Well-named tests read like a specification of the park, without looking at the implementation:

describe('DinosaurFeeder', () => {
  it('should feed herbivores plants only', () => {
    // This test clearly documents expected behavior
  });

  it('should not feed carnivores to each other', () => {
    // Business rule captured in a test!
  });
});

The descriptions in it are business rules that will not quietly go out of date like ordinary documentation, because the test would stop passing.

Better Design - TDD Enforces Loose Coupling

A class that creates its own database and mailer is hard to test, so TDD naturally leads to injecting dependencies through the constructor:

// TDD leads to Dependency Injection
class GoodParkManager {
  constructor(database, mailer) {
    this.database = database;
    this.mailer = mailer;
  }
}

// Easy to test with mocks:
const mockDb = { query: vi.fn() };
const manager = new GoodParkManager(mockDb, mockMailer);

In a test you pass in fakes (mocks), in production the real objects, and the class does not see the difference. This is the dependency inversion principle from the SOLID lesson.

TDD Anti-patterns - What to Avoid

Tests can be bad too. Compare two pairs of examples:

// ANTI-PATTERN: Test too general
it('should work', () => {
  expect(doSomething()).toBeTruthy();
});

// CORRECT: Specific test
it('should return dinosaur count for specific species', () => {
  expect(countDinosaurs('Velociraptor')).toBe(8);
});

// ANTI-PATTERN: Testing implementation instead of behavior
it('should call database.query', () => {
  service.getDinosaurs();
  expect(database.query).toHaveBeenCalled();
});

// CORRECT: Testing behavior
it('should return all dinosaurs from paddock', () => {
  const result = service.getDinosaurs();
  expect(result).toHaveLength(5);
});

A test that checks the call to database.query breaks with every change to the implementation, even though the behavior is correct. Test the result, not the way it was obtained.

TDD Tools

Vitest - Modern Framework

Vitest is a fast test runner compatible with the Jest API and a natural choice in Vite projects. You set the code coverage thresholds in the coverage.thresholds field:

// vitest.config.js
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    coverage: {
      provider: 'v8',
      thresholds: { statements: 80, branches: 80, functions: 80, lines: 80 }
    }
  }
});

Running the tests with coverage ends with an error when the result drops below 80%. Treat this threshold as an alarm, not a goal in itself.

In Jest you put the same threshold in the coverageThreshold field:

// jest.config.js
module.exports = {
  testEnvironment: 'node',
  coverageThreshold: {
    global: { statements: 80, branches: 80, functions: 80, lines: 80 }
  }
};

Both tools have a similar API (describe, it, expect), so switching between them is easy. In new projects I recommend Vitest, and in existing ones stay with Jest if it works well.

TDD is a powerful technique that changes the way you think about code. Instead of "write first, test later" you adopt the approach "define the expectations first, then implement". In the next lesson you will combine TypeScript with popular frameworks.

Remember: a test is a fence built before the dinosaur arrives, not after it escapes.

Code for this lesson: index.js
// SharedArrayBuffer and Atomics - shared memory between threads
console.log("Jurassic Park - DNA Shared Memory System");
console.log("SharedArrayBuffer and Atomics simulation\n");

// ====================================
// 1. SHAREDARRAY BUFFER - BASICS
// ====================================
console.log("=== 1. SharedArrayBuffer ===\n");

// Creating a SharedArrayBuffer (16 bytes = 4 x Int32)
const sharedBuffer = new SharedArrayBuffer(16);
const sharedView = new Int32Array(sharedBuffer);

console.log("SharedArrayBuffer created:");
console.log("  Size:", sharedBuffer.byteLength, "bytes");
console.log("  Int32 elements:", sharedView.length);

// Initializing values
sharedView[0] = 100; // Number of dinosaurs
sharedView[1] = 85;  // Security level
sharedView[2] = 0;   // Alert counter
sharedView[3] = 1;   // System status (1 = active)

console.log("\nInitial values:");
console.log("  Dinosaurs:", sharedView[0]);
console.log("  Security:", sharedView[1], "%");
console.log("  Alerts:", sharedView[2]);
console.log("  Status:", sharedView[3] === 1 ? "ACTIVE" : "INACTIVE");

// ====================================
// 2. ATOMICS - ATOMIC OPERATIONS
// ====================================
console.log("\n=== 2. Atomics operations ===\n");

// Atomics.add - add a value atomically
const previousAlerts = Atomics.add(sharedView, 2, 1);
console.log("Atomics.add(alerts, 1):");
console.log("  Previous value:", previousAlerts);
console.log("  New value:", Atomics.load(sharedView, 2));

// Atomics.sub - subtract a value atomically
const previousSafety = Atomics.sub(sharedView, 1, 10);
console.log("\nAtomics.sub(safety, 10):");
console.log("  Previous value:", previousSafety);
console.log("  New value:", Atomics.load(sharedView, 1));

// Atomics.exchange - swap a value
const oldStatus = Atomics.exchange(sharedView, 3, 0);
console.log("\nAtomics.exchange(status, 0):");
console.log("  Old value:", oldStatus);
console.log("  New value:", Atomics.load(sharedView, 3));

// Atomics.compareExchange - conditional swap
const result = Atomics.compareExchange(sharedView, 3, 0, 1);
console.log("\nAtomics.compareExchange(status, expected=0, new=1):");
console.log("  Result (previous):", result);
console.log("  Current value:", Atomics.load(sharedView, 3));

// ====================================
// 3. THREAD COMMUNICATION SIMULATION
// ====================================
console.log("\n=== 3. Thread communication simulation ===\n");

// Producer-consumer simulation with Atomics
class DinoMonitorSystem {
  constructor() {
    this.buffer = new SharedArrayBuffer(32);
    this.data = new Int32Array(this.buffer);
    // Indexes: 0=lock, 1=dinoCount, 2=alertCount, 3=safetyLevel
  }

  // Mutex simulation with Atomics
  acquireLock() {
    while (Atomics.compareExchange(this.data, 0, 0, 1) !== 0) {
      // Spin-wait (in real code: Atomics.wait)
    }
    console.log("  Lock acquired");
  }

  releaseLock() {
    Atomics.store(this.data, 0, 0);
    console.log("  Lock released");
  }

  // Add dinosaur (safely)
  addDinosaur() {
    this.acquireLock();
    const current = Atomics.load(this.data, 1);
    Atomics.store(this.data, 1, current + 1);
    console.log(`  Dinosaur added. Total: ${current + 1}`);
    this.releaseLock();
  }

  // Report alert (safely)
  reportAlert() {
    // Atomics.add is atomic on its own - no lock needed
    const prev = Atomics.add(this.data, 2, 1);
    console.log(`  Alert #${prev + 1} reported`);
  }

  getStatus() {
    return {
      dinosaurs: Atomics.load(this.data, 1),
      alerts: Atomics.load(this.data, 2),
      safety: Atomics.load(this.data, 3)
    };
  }
}

const monitor = new DinoMonitorSystem();

console.log("Simulation of operations from multiple threads:");
monitor.addDinosaur();
monitor.addDinosaur();
monitor.reportAlert();
monitor.addDinosaur();
monitor.reportAlert();

console.log("\nSystem state:", monitor.getStatus());

// ====================================
// 4. COMPARISON WITH A REGULAR BUFFER
// ====================================
console.log("\n=== 4. SharedArrayBuffer vs ArrayBuffer ===\n");

console.log("ArrayBuffer:");
console.log("  - Copied between threads (structured clone)");
console.log("  - Safe but slower");
console.log("  - No race condition problems");

console.log("\nSharedArrayBuffer:");
console.log("  - Shared between threads (zero-copy)");
console.log("  - Faster but requires synchronization");
console.log("  - Requires Atomics for safe access");
console.log("  - Requires COOP/COEP headers");

console.log("\nWhen to use SharedArrayBuffer:");
console.log("- Intensive numeric computations");
console.log("- Processing large data sets");
console.log("- Real-time applications (games, simulations)");
console.log("- Sharing state between Web Workers");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Useful articles