Deep equality and testing that code throws
The last test is wrong on purpose: a failing test can mean a bug in the test itself. Read the message before changing the code. (JSON.stringify is a quick deep check; real runners' toEqual also handles key order, undefined, Maps and more.)
A test is a small piece of code that runs your code with a known input and checks the result with an assertion; a test runner such as Vitest or Jest runs all your tests and reports which pass, so bugs are caught by a machine every time you change something.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Using the test and assertEqual helpers from the first live example, write three tests for isEven(n) (return n % 2 === 0;): a normal even number, an odd number, and the edge case 0.
Write the Vitest version of this: capitalize("asha") should be "Asha", capitalize("") should be "", and capitalize(5) should throw a TypeError.
Explain it without notes
What is the difference between an assertion, a test and a test runner?
What makes a good unit test?
Why do you need toEqual instead of toBe for arrays and objects?
What is a regression test, and why write one before fixing a bug?
Preview
Console
Nothing logged yet.Expected console output
[1, 2] === [1, 2] is false
PASS adds an item to a new array
PASS rejects 0 with a RangeError
PASS rejects text with a TypeError
FAIL rejects 11 with a TypeError → expected TypeError but got RangeError