0
0
Node.jsframework~5 mins

Node.js built-in test runner in Node.js

Choose your learning style9 modes available
Introduction

The Node.js built-in test runner helps you check if your code works correctly without extra tools.

You want to quickly test small parts of your Node.js code.
You need to run simple tests without installing extra packages.
You want to write tests that run automatically when you save files.
You want to check if a function returns the right result.
You want to organize tests in files and see clear pass/fail reports.
Syntax
Node.js
import test from 'node:test';
import assert from 'node:assert';

test('test name', () => {
  assert.strictEqual(actual, expected);
});

Use import test from 'node:test' to access the test runner.

Use assert to check if values are as expected.

Examples
This test checks if 1 + 1 equals 2.
Node.js
import test from 'node:test';
import assert from 'node:assert';

test('simple addition', () => {
  assert.strictEqual(1 + 1, 2);
});
This test checks if the string contains 'world'.
Node.js
import test from 'node:test';
import assert from 'node:assert';

test('string includes', () => {
  assert.ok('hello world'.includes('world'));
});
Sample Program

This program tests the multiply function with two cases: normal numbers and zero.

Node.js
import test from 'node:test';
import assert from 'node:assert';

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

test('multiply two positive numbers', () => {
  assert.strictEqual(multiply(3, 4), 12);
});

test('multiply by zero', () => {
  assert.strictEqual(multiply(5, 0), 0);
});
OutputSuccess
Important Notes

Run tests using node --test command in your terminal.

Test files should have .test.js or .spec.js extension for easy identification.

Use descriptive test names to understand what each test checks.

Summary

The Node.js built-in test runner lets you write and run tests easily without extra tools.

Use test() to define tests and assert to check results.

Run tests with node --test and see clear pass/fail reports.