brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: node --test runs your tests without installing a test framework

Web-Development
~/tips/tip-javascript-node-test-runner

test("async tests work too", async () => {

Runs tests with the test runner built into Node, no extra package needed.

For a small script or a side project I don’t want to add Jest or Vitest just to check three functions. Node ships its own test runner, and node --test is all you type.

Write a file such as sum.test.js with the built-in node:test module and node:assert:

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

test("adds numbers", () => {
  assert.strictEqual(1 + 2, 3);
});

test("async tests work too", async () => {
  const res = await Promise.resolve(42);
  assert.strictEqual(res, 42);
});

Then run:

node --test

Without arguments Node looks for files like *.test.js, *-test.js, test-*.js and anything under a test/ directory (also .mjs and .cjs). If any test fails, the process exits with code 1, so it works in CI as is.

A few options I’d keep in mind:

node --test --watch                         # rerun on file changes
node --test --test-name-pattern="adds"      # only matching test names
node --test --experimental-test-coverage    # coverage report

Caveat: the runner itself is marked stable in the Node docs, but watch mode and coverage are still experimental, so their flags and output can change between versions. Also it is plain by design: no snapshot matchers and no DOM, so for a React app you will still want a bigger tool.

Check node --version first. The docs list the runner as stable since v20.0.0.

Further reading: Node.js docs: Test runner

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link