typescript · level 3 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Unit tests check your code so you do not have to.
A runs one small piece of code with a known input and checks the answer. Professionals keep hundreds of them and run them after every change, so a bug shows up in seconds instead of weeks.
A is the code that runs every test and reports what passed. Ours is tiny. test takes a name and a callback and runs it inside try...catch. assertEqual<T> throws when two values differ, and the generic makes both sides the same type.
function assertEqual<T>(actual: T, expected: T): void {
if (actual !== expected) {
throw new Error(`expected ${String(expected)}, got ${String(actual)}`);
}
}
function test(name: string, run: () => void): void {
try {
run();
console.log(`PASS ${name}`);
} catch (e) {
console.log(`FAIL ${name}: ${String(e)}`);
}
}
test("trims spaces", () => assertEqual(" tea ".trim(), "tea")); String(e) turns a thrown Error into text like Error: expected 4, got 5.
guess first
Test the rounding. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function assertEqual<T>(actual: T, expected: T): void {
if (actual !== expected) {
throw new Error(`expected ${String(expected)}, got ${String(actual)}`);
}
}
function test(name: string, run: () => void): void {
try {
run();
console.log(`PASS ${name}`);
} catch (e) {
console.log(`FAIL ${name}: ${String(e)}`);
}
}
test("rounds halves", () => { assertEqual(Math.round(2.5), 3); assertEqual(Math.round(-2.5), -3); });
your turn
Your turn. Write a test case of your own.
Add a second test for discount: give it a name, a price, a percentage, and the answer you expect. Make it pass.
fix it
The lists match, but the test fails. Fix the test.
- The message says it expected
[1,2,3]and got[1,2,3]. They look the same, so why fail? !==on two arrays asks whether they are the very same array, not whether they hold the same items.- On line 2, compare
JSON.stringify(actual)withJSON.stringify(expected)instead.
nailed it
your code now checks itself. :D
- A unit test runs code with a known input and checks the answer.
- A test runner catches each failure, so one FAIL never stops the rest.
===compares arrays by identity, so compare their contents instead.
new words in your collection
- unit test
- test runner
This lesson isn’t saved. A free account remembers every lesson you finish.