Advanced · 12 min
Test small functions
Check normal cases, boundaries, and rejected inputs with explicit assertions.
Make a failure visible
A small assertion can throw when the actual result differs from the expected one. A test that never checks a result can pass while the function is wrong.
function assertEqual(actual, expected) { if (actual !== expected) throw new Error("Mismatch"); }
function total(price, quantity) { return price * quantity; }
assertEqual(total(4, 3), 12);
assertEqual(total(4, 0), 0);
console.log("2 checks passed");Output
2 checks passed
Test rejected input
Check that invalid input actually throws. Keep the test failure outside the try block so it is not accidentally caught as the expected error.
function quantity(value) { if (value < 0) throw new Error("Negative"); return value; }
let threw = false;
try { quantity(-1); } catch { threw = true; }
if (!threw) throw new Error("Expected rejection");
console.log("Invalid input rejected");Output
Invalid input rejected
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Fix the implementation
Make total pass both the regular case and the zero-quantity case. Keep the checks unchanged.
Multiply price by quantity inside total.