Skip to content
jshacks.dev
Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read
Summarize in AI

node:test has the same describe and it words as Jest and Mocha, so tests can be grouped and read as a spec.

cart.test.mjsJavaScript
import { describe, it, beforeEach } from 'node:test';
import assert from 'node:assert/strict';

describe('cart', () => {
  let items;

  beforeEach(() => {
    items = [];
  });

  it('starts empty', () => {
    assert.equal(items.length, 0);
  });

  describe('adding', () => {
    it('adds an item', () => {
      items.push('book');
      assert.deepEqual(items, ['book']);
    });
  });
});
Text
▶ cart
  ✔ starts empty (0.4ms)
  ▶ adding
    ✔ adds an item (0.2ms)
  ▶ adding (0.5ms)
▶ cart (1.6ms)
ℹ tests 2
ℹ suites 2
ℹ pass 2
ℹ fail 0

The timings will differ, and the summary lines after fail are omitted. Suites appear as ▶ lines in the spec reporter, and each test shows ✔ or ✖. beforeEach runs before every test in the suite and inside nested suites, so items is fresh each time. describe and it are aliases for suite and test, as the documentation explains.

Prefer a fresh object per test over shared mutable state. after and afterEach clean up, and a hook that throws fails the tests it covers.

Also inNode.js
Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.