Why do testing?
Automated tests check that your code does what it should. They give you confidence to change the code without fear of breaking something (the tests warn you).
A basic assertion
An assertion checks that a condition holds; if not, it fails.
function assert(condition, message) {
if (!condition) throw new Error(message || "Assertion failed");
}
function double(x) {
return x * 2;
}
assert(double(4) === 8, "double(4) should be 8");
assert(double(0) === 0, "double(0) should be 0");
console.log("✅ All tests passed");
Testing frameworks
In real projects, tools like Jest or Vitest are used, with a declarative syntax:
test("double multiplies by two", () => {
expect(double(4)).toBe(8);
});
TDD: Test-Driven Development
Test-driven development reverses the usual order. The cycle is red → green → refactor:
- Red: write a test that fails (the function does not exist yet).
- Green: write the minimum code to make it pass.
- Refactor: improve the code while keeping the tests green.
TDD forces you to think first about what the code should do before how.
Examples
Homemade mini test suite
function assert(cond, msg) {
if (!cond) throw new Error(msg);
}
function isEven(n) {
return n % 2 === 0;
}
assert(isEven(4) === true, "4 is even");
assert(isEven(7) === false, "7 is odd");
console.log("All tests passed");