Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Node.js Unit Testing
Node.js Intermediate FREE

Unit Testing

Lesson 1 of 17 Intermediate Interactive

Unit tests verify individual functions or components in isolation.

Syntax

NODEJS
const assert = require('assert');

function add(a, b) { return a + b; }

assert.strictEqual(add(1, 2), 3);
assert.strictEqual(add(-1, 1), 0);
Unit Testing with Jest
NODE
// math.js
function add(a, b) { return a + b; }
function divide(a, b) {
    if (b === 0) throw new Error("Cannot divide by zero");
    return a / b;
}

// math.test.js
// describe("Math", () => {
//     test("add", () => {
//         expect(add(2, 3)).toBe(5);
//     });
//     test("divide", () => {
//         expect(divide(10, 2)).toBe(5);
//     });
//     test("divide by zero", () => {
//         expect(() => divide(1, 0)).toThrow();
//     });
// });