🟨 JavaScript tutorial for beginners · Class 9 · Lesson 17 of 18 · Free
Testing Your Code – Write Tiny Tests in JavaScript
⏱ About 30 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Write tests with console.assert and your own check() function
- Test arrays, objects, edge cases and errors correctly
- Find and fix a bug by letting a test point to it
Before a long train journey, you check your bag: ticket, water bottle, charger, tiffin. Two minutes of checking saves you a big problem later. Tests are a checklist for your code: tiny programs that check your functions still give the right answers — every time you change something.
What is testing in JavaScript and why should I do it?
A test calls your function with an input where you ALREADY know the right answer, and compares. If the answer is wrong, the test tells you at once.
Look at `getGrade` below. It looks fine. But the tests show a bug at exactly 90 marks. Can you find it before you run?
Without tests, this bug might reach a real report card. With tests, you catch it in one second.
1function getGrade(marks) {2 if (marks > 90) return "A";3 if (marks >= 75) return "B";4 if (marks >= 50) return "C";5 return "D";6}7▶console.log("95 →", getGrade(95), "(want A)");9console.log("90 →", getGrade(90), "(want A)");10console.log("75 →", getGrade(75), "(want B)");11console.log("40 →", getGrade(40), "(want D)");
No variables yet.
▌✏️ Change this code and run it yourself
95 → A (want A)90 → B (want A)75 → B (want B)40 → D (want D)
💡 Try it: fix the bug (> should be >=) and run again — every line now matches.
How do I use console.assert in JavaScript?
`console.assert(condition, message)` is a test built into JavaScript. If the condition is true, it stays silent. If it is false, it prints "Assertion failed" and your message.
Silence means success. So add a final "Tests finished" line, or you will not know the tests ran at all.
totalMarks uses reduce from Lesson 2. Small functions like this are perfect to test, because they always give the same output for the same input.
Assertion failed: this test is wrong on purposeTests finished
💡 Only the wrong test prints. Fix 99 to 100 and the console shows only "Tests finished".
How do I write my own test function in JavaScript?
Let us make a friendlier tester. `check(name, actual, expected)` prints ✅ or ❌ and, when it fails, shows both values. That helps you see WHAT went wrong.
It also counts passes, so at the end you get a score like "3/4 tests passed".
Real testing tools (Jest, Vitest) work the same way: `expect(actual).toBe(expected)` is just a fancy check().
▶let passed = 0;2let total = 0;3function check(name, actual, expected) {4 total++;5 if (actual === expected) {6 passed++;7 console.log("✅", name);8 } else {9 console.log("❌", name, "| got", actual, "| expected", expected);10 }11}1213const ticketPrice = (age) => (age < 12 ? 50 : 100);14check("child of 8", ticketPrice(8), 50);15check("adult of 30", ticketPrice(30), 100);16check("exactly 12", ticketPrice(12), 100);17check("senior of 65", ticketPrice(65), 60);18console.log(`${passed}/${total} tests passed`);
No variables yet.
▌✏️ Change this code and run it yourself
✅ child of 8✅ adult of 30✅ exactly 12❌ senior of 65 | got 100 | expected 603/4 tests passed
💡 The senior test fails because the rule for 60+ is missing. Try it: add age >= 60 ? 60 : … to ticketPrice.
How do I test arrays and objects?
Trap! `[1, 2] === [1, 2]` is false. `===` on arrays and objects asks "is this the SAME object?", not "do they look the same?".
An easy fix for simple data: turn both into JSON text with `JSON.stringify` (Lesson 9) and compare the strings.
Keep the keys in the same order — `{a:1, b:2}` and `{b:2, a:1}` give different JSON strings.
with === : falsewith sameData: true
💡 Try it: change Rohan's marks to 90 — which test result changes?
How do I test edge cases and errors?
Bugs love the edges: 0, the exact border value (like 33 for pass), negative numbers, empty lists, wrong types. Always add tests for them.
A good function THROWS an error for nonsense input, like −5 marks. To test that, call it inside try/catch and check that an error really came.
Tip: write the tests first, then the function. This is called Test-Driven Development (TDD).
Pass Fail Fail Pass✅ negative marks | Marks must be a number from 0 to 100✅ text instead of number | Marks must be a number from 0 to 100
💡 We pass an arrow function () => passOrFail(-5), so the error happens INSIDE checkThrows's try, not before it.
How do I test code that changes a web page?
You can test the DOM too. Call your function, then check the element's `textContent` or `classList`.
`btn.click()` pretends a user clicked, so you can test event handlers without touching the mouse.
Press ▶ Run: the tests click the button for you and check the page.
📄 HTML of the page (tap to see / edit)
✅ starts at 0✅ two clicks make 8Page now says: Score: 8
💡 Try it: change runs += 4 to runs += 6 and see which test fails.
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
console.assert(2 + 2 === 4, "Maths broke");
console.assert("5" === 5, "Types differ");
console.log("Done");Question 2. What does this print?
const a = [1, 2]; const b = a; console.log(a === b, a === [1, 2]);
Question 3. What does this print?
const total = 0.1 + 0.2; console.log(total === 0.3, Math.abs(total - 0.3) < 0.0001);
🧩 Your challenge
Bug hunt with tests! `autoFare(km)` should charge ₹30 for the first 2 km, then ₹15 for every extra km. Write check() and these 5 tests: 1 km → 30, 2 km → 30, 3 km → 45, 10 km → 150, 0 km → 30. Run them — some fail. Use the failing tests to find and fix the bug, until you see: ✅ 1 km ✅ 2 km ✅ 3 km ✅ 10 km ✅ 0 km 5/5 tests passed
✅ 1 km ✅ 2 km ✅ 3 km ✅ 10 km ✅ 0 km 5/5 tests passed
⚠️ Common mistakes (and how to fix them)
❌ Wrong
const evens = [1, 2, 3, 4].filter((n) => n % 2 === 0);
if (evens === [2, 4]) console.log("✅ evens");
else console.log("❌ evens");No error, but the test prints ❌ even though the function is correct — the test itself is buggy.
✅ Right
const evens = [1, 2, 3, 4].filter((n) => n % 2 === 0);
if (JSON.stringify(evens) === JSON.stringify([2, 4])) console.log("✅ evens");
else console.log("❌ evens");=== checks whether two arrays are the same object, not whether they hold the same values. Compare JSON strings (or each item).
❌ Wrong
const total = 90 + 5;
console.assert("Total should be 100", total === 100);
console.log("All tests passed!");No error, but the assert stays silent and says nothing about the wrong total (95) — the test can never fail.
✅ Right
const total = 90 + 5;
console.assert(total === 100, "Total should be 100");
console.log("Tests finished");The condition comes FIRST, the message second. A non-empty string is always truthy, so the wrong order never fails.
❌ Wrong
function passOrFail(marks) {
if (marks < 0) throw new Error("Marks cannot be negative");
return marks >= 33 ? "Pass" : "Fail";
}
console.log(passOrFail(-5));
console.log("✅ more tests here…");Error: Marks cannot be negative
✅ Right
function passOrFail(marks) {
if (marks < 0) throw new Error("Marks cannot be negative");
return marks >= 33 ? "Pass" : "Fail";
}
try {
passOrFail(-5);
console.log("❌ no error thrown");
} catch (err) {
console.log("✅ throws:", err.message);
}
console.log("✅ more tests here…");An error that nobody catches stops the whole program, so the other tests never run. Test errors inside try/catch.
📌 Remember
- A test runs your function on an input with a known answer and compares.
- console.assert(condition, message) prints only when the condition is false.
- A check(name, actual, expected) helper shows ✅/❌ and a score like 5/5.
- Compare arrays and objects with JSON.stringify, decimals with "close enough".
- Always test edges (0, borders, empty, wrong type) and test errors with try/catch.
Finished the quiz and the challenge?
Questions students ask
What is unit testing in JavaScript?
A unit test checks one small piece of code, usually one function, on its own. You give it an input and compare the output with the answer you expect. Many small unit tests together make you confident the whole app works.
What is Jest and do I need it?
Jest and Vitest are popular testing tools for JavaScript projects. You install them with npm and run all tests with npm test. They give nicer reports, but the idea is exactly the check() function you wrote today, so you do not need them to start.
How many tests should I write?
Start with one normal case, each border value and one bad input for every important function. When you find a bug, first write a test that fails because of it, then fix it — that bug can never come back unnoticed.
Is testing the same as debugging?
No. Debugging (Class 8 Lesson 17) is finding why something is broken. Testing is checking automatically whether something is broken. Tests tell you WHERE to start debugging.