The discount bug you fixed last month is back. This week a teammate tidied the same function, and your fix was deleted with it. Nobody noticed, because no test was guarding that fix.
TDD and CI close that gap from two sides. TDD (Test-Driven Development) means writing the test before the code, then writing code until that test passes. CI (Continuous Integration) means a server runs all those tests automatically. It does so at every push (your code changes are sent to GitHub) or pull request (a request to merge your changes into the main code). Picture a tailor making a shirt. They make a pattern from your measurements first, and only then cut the cloth. While the cut doesn't fit the pattern, the shirt isn't done. Once it fits, they tidy the seams, and the size must not change. In this picture, the pattern is the test, cutting the cloth is writing the code, a cut that fits is a test that passes, and tidying the seams is the refactor.
The Red, Green, Refactor cycle
TDD runs in short loops, always in this order:
- Red: write one test for the next behaviour, run it, and watch it fail (red).
- Green: write the least code that makes that test pass (green).
- Refactor: tidy the code without changing what it does. Every test must stay green.
Then start again from Red for the next behaviour. The main benefit: every line of code is written to make one test pass. Because the test was written first, the code is more surely correct. TDD doesn't make the code finish faster. It also doesn't give 100% test coverage (all of the code run by the tests) on its own.
The example in this lesson is the function calculateDiscount(total). It calculates the shopping total after the discount, with the rules in the table below. The Lab uses the same rules with the name hitungDiskon and amounts 1,000 times larger (100,000 and 500,000).
| Shopping total | Result | Example |
|---|---|---|
| below 0 | 0 |
calculateDiscount(-100) gives 0 |
| 0 up to $100 | no discount | calculateDiscount(50) gives 50 |
| above $100 up to $500 | 10% off | calculateDiscount(200) gives 180 |
| above $500 | 20% off | calculateDiscount(1000) gives 800 |
Red: watch the test fail first
The first loop tests a negative total. The function calculateDiscount exists, but it is still empty.
// discount.test.js
import { describe, it, expect } from "vitest";
import { calculateDiscount } from "./discount";
describe("calculateDiscount", () => {
it("returns 0 for a negative total", () => {
expect(calculateDiscount(-100)).toBe(0);
});
});
// discount.js
export function calculateDiscount(total) {}
npx vitest run answers:
× discount.test.js > calculateDiscount > returns 0 for a negative total 3ms
→ expected undefined to be +0 // Object.is equality
An empty function returns undefined, so the test is red. Red here is good news: it proves the test can fail. A test that's green right away while the code is empty almost surely checks nothing, usually because its expect was never written.
Green: the least code that passes
Then add the least code that makes the first test pass:
export function calculateDiscount(total) {
if (total < 0) return 0;
}
One line is enough, and the first test is green. There's no return total yet, because no test asks for it yet. The second loop adds a test: calculateDiscount(50) must give 50. That test is red (expected undefined to be 50), then return total; makes it green. And so on until all four rule rows in the table have a test. In the 20% loop the test is red with expected 900 to be 800, because the code still takes 10% off.
Refactor: tidy up, tests stay green
Once all four tests are green, the code gets tidied. The magic numbers (numbers written straight into the code with no name) get names. The order of the ifs is made clear:
const NO_DISCOUNT_LIMIT = 100;
const SMALL_DISCOUNT_LIMIT = 500;
export function calculateDiscount(total) {
if (total < 0) return 0;
if (total <= NO_DISCOUNT_LIMIT) return total;
if (total <= SMALL_DISCOUNT_LIMIT) return total * 0.9;
return total * 0.8;
}
total < 0handles input that makes no sense first.<=makes a number exactly on a limit take the lower tier, the one with the smaller discount.calculateDiscount(100)stays100, andcalculateDiscount(500)gives450(10% off, not 20%).total * 0.9means 10% off, andtotal * 0.8means 20% off.
A refactor has one condition: the behaviour doesn't change, so every test stays green. But be careful: none of the four tests sits exactly on a limit. If both <= accidentally become <, all four tests stay green, while calculateDiscount(500) gives 400. That's why you add tests for $100 and $500.
The exercises: the test first, then the code
In the first exercise, you finish calculateDiscount from above. The starter code already has the function runTddTests(), which tests four cases and counts how many pass. That number is printed, so when everything is right, the console writes 4.
The next two exercises use isPalindrome(str). This function answers true when the text reads the same backwards, like "level". Here are the function and its two tests:
function isPalindrome(str) {
const text = str.toLowerCase();
return text === text.split("").reverse().join("");
}
describe("isPalindrome", () => {
it("true for a palindrome", () => {
expect(isPalindrome("level")).toBe(true);
});
it("false for an ordinary word", () => {
expect(isPalindrome("hello")).toBe(false);
});
});
toLowerCase()changes every letter to lowercase, so"Level"counts as a palindrome too.split("")breaks the text into letters,reverse()flips their order, andjoin("")joins them again.expect(isPalindrome(...))checks the result of calling the function, not a value typed in directly.- The second test checks a case that must be rejected (
toBe(false)). A test that only proves the true case doesn't prove much, because a function that always answerstruepasses it too. In the exercise, an ordinary word like"learning"must answerfalsetoo.
CI: tests run on their own at every push
CI stands for Continuous Integration: code from many developers is merged as often as possible, and every merge is checked automatically. CD continues from there, with two meanings. Continuous Delivery: code that passes is always ready to release. Continuous Deployment: code that passes is released automatically. The chain of automatic CI and CD steps is often called a pipeline. On GitHub, the tool is GitHub Actions. You write its steps in one YAML file (a text format for settings) in the folder .github/workflows/. That file is called a workflow:
# .github/workflows/test.yml
name: Test
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- run: npm ci
- run: npx vitest run
on: pushandon: pull_requestare the triggers. The tests run automatically at every push or pull request tomain(the main branch of the code).jobsholds the jobtest: its steps (steps) run on an Ubuntu machine owned by GitHub.uses:uses an action (a ready-made step), for exampleactions/checkout, which fetches your code from GitHub.run:runs one terminal command.npm ciinstalls the dependencies (the libraries your project uses) exactly aspackage-lock.jsonlists them.- If one test fails,
vitest runexits with code 1 (a sign of failure), so the job goes red. @v7is the latest major version (the first number of the version) of both actions (November 2026). The actions' own code runs on Node 24 (not the Node 22 for your tests). Older tutorials often write@v4, which was made for Node 20, but GitHub removed Node 20 from Actions in September 2026.
In your project's settings on GitHub, a branch protection rule (it guards a branch) can require the test job to pass. Then a pull request whose tests are red can't be merged (joined into main).
⚠️ What makes TDD lose its point
- Code first, tests later. The order "write the code, write the tests, run them, refactor" isn't TDD. In TDD the test is written first and must be seen red first.
- A test with no
expect. It is green right away even though the code is empty. If a new test is never red, suspect the test. - The wrong side of a limit. The choice of
<or<=at $100 and $500 decides the result. Always write a test exactly on the limit. - A refactor that changes behaviour. If a test fails during a refactor, it isn't a refactor, it's a new bug.
TL;DR: TDD (Test-Driven Development) means writing the test before the code. Its loop is Red, Green, Refactor: write a test and watch it fail (red), write the least code until it passes (green), then tidy the code with every test still green. Red first proves the test can fail, and the code is more surely correct because its test came first. For calculateDiscount (the shopping total after the discount): below 0 gives 0, up to $100 no discount, up to $500 10% off, and above that 20%. A number exactly on a limit takes the lower tier, the one with the smaller discount (<=). CI (Continuous Integration) runs the tests automatically at every push (changes sent to GitHub) or pull request (a request to merge changes). On GitHub, CI runs through GitHub Actions, and branch protection (a rule that guards a branch) can refuse a merge whose tests are red.
⚡ Red, Green, Refactor
Meaning: TDD (Test-Driven Development) means writing the test before the code. One TDD loop always has this order: Red (write a test, watch it fail), Green (write the least code until the test passes), then Refactor (tidy the code, every test stays green). The benefit: the code is more surely correct because its test was written first.
⚡ Red first: watch the test fail
Write:
it("returns 0 for a negative total", () => {
expect(calculateDiscount(-100)).toBe(0);
});
export function calculateDiscount(total) {}
Guess first: the function calculateDiscount is still empty, so the test is red with expected undefined to be +0. Is that bad news or good news?
Good news: it proves the test can fail. A test that's green right away while the code is empty almost surely checks nothing.
Meaning: calculateDiscount(total) calculates the shopping total after the discount, and a negative total must give 0. Once you have seen the test red, write the least code that turns it green: if (total < 0) return 0;.
⚡ CI: tests run on their own at every push
Write:
on:
push:
branches: [main]
pull_request:
branches: [main]
Meaning: This is part of a workflow file for GitHub Actions, GitHub's CI service (a server that runs the tests automatically). At every push (changes sent to GitHub) or pull request (a request to merge changes) to the branch main, the tests run. Branch protection (a rule that guards a branch) can require the tests to pass, so a pull request whose tests are red can't be merged (joined).