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.
node:test has the same describe and it words as Jest and Mocha, so tests can be grouped and read as a spec.
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']);
});
});
});▶ cart
✔ starts empty (0.4ms)
▶ adding
✔ adds an item (0.2ms)
▶ adding (0.5ms)
▶ cart (1.6ms)
ℹ tests 2
ℹ suites 2
ℹ pass 2
ℹ fail 0The 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.