Money, coupon and errors: the cases that break
level 2 · 25 min · edge cases (TDD)
Money, typed text and invalid input are where code that “works” tends to break. In JavaScript, 0.1 + 0.2 gives 0.30000000000000004; a coupon arrives in upper or lower case; a cart can be empty.
In TDD, each of these cases goes into the test list before any code exists. You pick one, watch the test fail, write the minimum to pass and check that the previous ones still pass.
Rule of thumb. For each rule, ask what usually breaks: empty values, rounding, upper and lower case, and invalid input. Write the failing test before the code that makes it pass.
Build the test list
The function cartTotal(items, coupon) adds up the cart and applies a coupon. These are the rules as a test list. The two visible tests cover only the happy path.
| Rule | Input | Expected output | Visible tests |
|---|---|---|---|
| Sums price times quantity | [{ price: 5, quantity: 2 }, { price: 3, quantity: 1 }] | 13 | covers |
| The coupon SAVE10 takes off 10% | [{ price: 50, quantity: 2 }], "SAVE10" | 90 | covers |
| An empty cart is worth 0 | [] | 0 | does not cover |
| Rounds to cents (0.1 + 0.2) | [{ price: 0.1, quantity: 1 }, { price: 0.2, quantity: 1 }] | 0.3 | does not cover |
| Also rounds the discounted total | [{ price: 9.99, quantity: 1 }], "SAVE10" | 8.99 | does not cover |
| The coupon code ignores upper and lower case | [{ price: 20, quantity: 1 }], "save10" | 18 | does not cover |
| An unknown coupon is an error | [{ price: 20, quantity: 1 }], "FREE" | throws Error("Unknown coupon") | does not cover |
| A quantity below 1 is an error | [{ price: 20, quantity: 0 }] | throws Error("Invalid quantity") | does not cover |
Exercise: write the code
Your code must pass the visible tests and the hidden checks, which cover the rest of the list.
Write cartTotal(items, coupon). items is an array of { price, quantity }; coupon is optional.
Rules: the total is the sum of price × quantity, rounded to 2 decimal places; an empty cart totals 0; the coupon "SAVE10" takes 10% off the sum, and coupon codes ignore case; any other coupon throws Error("Unknown coupon"); a quantity below 1 throws Error("Invalid quantity").
Visible tests
test("adds price times quantity", () => {
expect(cartTotal([{ price: 5, quantity: 2 }, { price: 3, quantity: 1 }])).to.equal(13);
});
test("applies SAVE10", () => {
expect(cartTotal([{ price: 50, quantity: 2 }], "SAVE10")).to.equal(90);
});