Assertions & edge cases
Test your own code
Lesson 14 of 20 · 12 min · Module 4: Reliable code
Professional developers write tests: small functions that run the code with known inputs and complain when the result is wrong. Tests catch mistakes immediately and let you change code with confidence.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Write assertions that fail loudly
- Pick edge cases that reveal bugs
- Make sure a test can actually fail
The idea
An assertion checks one expectation and throws an Error when it fails. A test function contains several of them, covering a normal case, edge cases (empty input, spaces at the edges, repeated symbols), and tricky input. Tools such as Vitest or Jest run many such tests automatically.
function assertEqual(actual, expected) {
if (actual !== expected) throw new Error(`expected ${expected}, got ${actual}`);
}
assertEqual(2 + 2, 4);
console.log("passed");
01An assertion is a tiny if
assertEqual compares and throws a descriptive Error when the values differ. If testSlugify finishes without throwing, every expectation held.
02Edges hide the bugs
Most broken slugify versions still turn "Hello World" into "hello-world". They fail on leading spaces, trailing punctuation, or repeated symbols, so those cases matter most.
const broken = t => t.toLowerCase().replace(/[^a-z0-9]+/g, "-");
console.log(broken(" Hi! "));-hi-03Break it on purpose
A test that cannot fail proves nothing. Changing the code briefly, as these checks do, shows that the test really guards the behaviour you care about.
Your turn
function slugify(text): lowercase, every run of characters that are not a–z or 0–9 becomes one hyphen, no hyphens at the start or end. Then write function testSlugify() with at least four assertions that throw when slugify is wrong. The checks will replace slugify with broken versions and expect your test to throw, so declare both with function.What the checks look for
- slugify handles titles, punctuation and spaces
- testSlugify passes with your slugify
- testSlugify catches a version that keeps edge hyphens
- testSlugify catches a version that only lowercases
Take this with you
Good tests describe the behaviour precisely enough that broken code fails them.
Go a little further
Install Vitest in a small project on your computer and rewrite testSlugify with its expect(...).toBe(...) syntax.