The TDD Mindset: Thinking in Tests

Introduction and Overview

By now, you should be familiar with the basics of Test-Driven Development (TDD) and its iterative Red-Green-Refactor cycle. This lesson focuses on honing your TDD mindset, a perspective that prioritizes writing tests before coding, which can dramatically improve code clarity, reliability, and maintainability.

We'll continue using TypeScript and Jest, tools that streamline our test-driven approach in TypeScript projects. Though we use Jest for its popularity and integration ease, other alternatives such as Mocha and Chai exist for different preferences or project requirements.

Let's explore this mindset further with practical examples and visualize the flow of thinking in tests.

Example: `calculateTotal` Function (Red Phase)

Let's begin by writing tests for a function named calculateTotal, designed to compute the total price of items in a shopping cart. Here is where you engage with the Red phase: Write a failing test.

Let's think about how to build a function that calculates lists of items. What should the interface be? How does the consumer of the code use it? These are the questions we think about first when we "think in tests". Here's one way we might think about it.

TypeScript
import { calculateTotal } from '../src/cart';

describe('calculateTotal function', () => {
  it('should return 0 for an empty cart', () => {
    const total = calculateTotal([]);
    
    expect(total).toBe(0);
  });
});

Explanation:

  • We know we want a function called calculateTotal() so we'll write a test that uses it.
  • For now, we know that we want an empty array as an input to return 0, so we can write that test.
  • The expectation is that these tests will initially fail, which is an integral part of the Red phase.

Running these tests confirms they fail, creating a clear path for subsequent development.

Example: Passing the Tests (Green Phase)

Now, let’s move to the Green phase where we implement the minimal code to pass these tests.

Implement the calculateTotal function in cart.ts:

export function calculateTotal(items: any[]): number {
  return 0;
}

Explanation:

  • The calculateTotal function takes an array of any objects. We don't really know the shape of the data yet and that's OK!
  • Returning 0 is enough to get the test to pass.

By running the test suite again, we should see all tests passing, demonstrating that our function meets the required condition.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal