0
0
Node.jsframework~5 mins

Writing test cases in Node.js

Choose your learning style9 modes available
Introduction

Writing test cases helps check if your code works correctly. It finds mistakes early so your program runs smoothly.

When you want to make sure a function returns the right result.
Before changing code to avoid breaking existing features.
To check if your app handles errors properly.
When you want to automate checking your code instead of testing manually.
To help others understand how your code should behave.
Syntax
Node.js
import assert from 'assert';
describe('Feature or function name', () => {
  it('should do something expected', () => {
    const result = functionToTest();
    assert.strictEqual(result, expectedValue);
  });
});

describe groups related tests.

it defines a single test case with a clear goal.

Examples
This test checks if adding 2 and 3 equals 5.
Node.js
import assert from 'assert';

describe('Addition function', () => {
  it('adds two numbers correctly', () => {
    const sum = 2 + 3;
    assert.strictEqual(sum, 5);
  });
});
This test checks if the greet function returns the right message.
Node.js
import assert from 'assert';

function greet(name) {
  return `Hello, ${name}!`;
}

describe('Greet function', () => {
  it('returns greeting with name', () => {
    assert.strictEqual(greet('Alice'), 'Hello, Alice!');
  });
});
Sample Program

This test suite checks the multiply function with different inputs: positive, zero, and negative numbers.

Node.js
import assert from 'assert';

function multiply(a, b) {
  return a * b;
}

describe('multiply function', () => {
  it('multiplies positive numbers', () => {
    assert.strictEqual(multiply(3, 4), 12);
  });

  it('multiplies by zero', () => {
    assert.strictEqual(multiply(5, 0), 0);
  });

  it('multiplies negative numbers', () => {
    assert.strictEqual(multiply(-2, 3), -6);
  });
});
OutputSuccess
Important Notes

Use clear test names to understand what each test checks.

Run tests often to catch errors early.

Keep tests small and focused on one thing.

Summary

Test cases check if code works as expected.

Use describe and it to organize tests.

Write simple tests for different input cases.