javascript · level 3 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A runs your code and asserts what the answer should be.
Checking output by eye stops working once a program grows. A test does the checking for you: run a function with a known input and compare the real answer with the one you expect.
The comparison is an . assertEqual below throws when the two differ, so a wrong answer can never slip past. Two arrays are only === when they are the very same array, so it compares their JSON text instead.
Test the normal cases and the edge cases: empty arrays, zero, the first and the last item.
function assertEqual(actual, expected) {
const a = JSON.stringify(actual);
const e = JSON.stringify(expected);
if (a !== e) { throw new Error(`Expected ${e} but got ${a}`); }
console.log(`ok ${a}`);
}
function evens(numbers) { return numbers.filter((n) => n % 2 === 0); }
assertEqual(evens([1, 2, 3, 4]), [2, 4]);
assertEqual(evens([]), []);
assertEqual(evens([7]), []); Write the expected answer yourself, by hand, before you run the code.
guess first
Three assertions about tags. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function assert(condition, message) {
if (!condition) { throw new Error(message); }
console.log(`passed: ${message}`);
}
const tags = ["new", "sale"];
assert(tags.length === 2, "two tags");
assert(tags.includes("sale"), "has sale");
assert(tags === ["new", "sale"], "same tags");
your turn
Your turn. Add a test of your own.
In the middle assertion, pick two or more numbers and type the average you expect. If your expected answer is wrong, the assertion will tell you.
fix it
The test caught a bug. Can you fix it?
- The first assertion says it expected toast but got undefined. Which index does
lastItemread? - Indexes start at 0, so the last item sits one before
items.length. - On line 7, change
items[items.length]toitems[items.length - 1], then press run.
nailed it
your code checks itself now. :D
- A test compares a real answer with the expected one.
- An assertion throws as soon as something is wrong.
- Always test edge cases like empty arrays and zero.
new words in your collection
- test
- assertion
- edge case
This lesson isn’t saved. A free account remembers every lesson you finish.