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.
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.
Explanation:
- We know we want a function called so we'll write a test that uses it.
