Nodejs test runner tips and tricks

Image of Author
September 21, 2023 (last updated September 21, 2023)

VSCode testing setup

See Nodejs test runner setup in VSCode

history

As of nodejs v20, the nodejs test runner is stable.

Its original test reporter was tap, but at some point in v19 is was defaulted to spec in terminal, which is much more readable (docs).

As of v20 there is an experimental watcher mode that (at least) works well for simple unit tests (docs).

test file naming

Almost any file with test in the name somewhere will be picked up as a test file (docs). I use the file.test.js idiom, usually.

runner

node --test # optional file/folder specification
node --test --watch . # file/folder must be specified

skip and only tests

There is a way to run only tests and skip tests, but I don't that it is particularly amenable to automation and hotkeys, since you have to pass a CLI flag. Instead I am highlighting the test name and then running the test name filter via hotkey. This is equivalent to an only-test.

test examples

import { test } from 'node:test'
import assert from 'node:assert/strict'

test('...', () => {
  assert.equal(actual(), expected)
})

test('...', async () => {
  assert.equal(await actual(), expected)
})

test('...', () => {
  assert.throws(() => {
    somethingThatThrows();
  })
})