Course contentsShow
← JavaScript
Lesson 2654 of 2,72354. Testing in JavaScriptFree lesson

Running Tests with Node Test Runner

Writing and executing basic tests using node:test module and the node --test CLI flag.

Running Tests with Node Test Runner

You'll learn how to write and execute basic tests using Node's built-in node:test module.

The Core Concept

Node's built-in test runner lets you write tests directly in JavaScript files without installing external libraries. You import the test function from the node:test module, define test cases with descriptive names, and run them using the node --test CLI flag.

Think of it like this: instead of needing a separate tool (like a special calculator app), Node now has testing built right into the language itself—just import what you need and run your tests with a simple command.

Writing Your First Test

import { test } from 'node:test';
import assert from 'node:assert';

test('addition works correctly', () => {
  const result = 2 + 2;
  assert.strictEqual(result, 4);
});

test('string concatenation', () => {
  const greeting = 'Hello' + ' ' + 'World';
  assert.strictEqual(greeting, 'Hello World');
});

Save this as example.test.js.

Running Tests from the Command Line

Execute your tests with:

node --test

Node automatically discovers files matching patterns like *.test.js, *_test.js, or files in a test/ directory. You can also target specific files:

node --test example.test.js

The output shows which tests passed or failed, with helpful error messages for failures.

What You Get

Each test runs in isolation. If one fails, the others still execute. The runner reports results clearly: green checkmarks for passes, detailed stack traces for failures.

Key Takeaway: Node's built-in test runner eliminates external dependencies for basic testing—just import test from node:test, write your test functions, and run node --test to execute them.