typestar

Hooks in JavaScript

before and after run once; the each variants run per test.

import { after, afterEach, before, beforeEach, describe, it }
  from "node:test";
import assert from "node:assert/strict";

describe("session", () => {
  let session;
  const log = [];

  before(() => log.push("open"));
  after(() => log.push("close"));
  beforeEach(() => { session = { runs: [] }; });
  afterEach(() => log.push("reset"));

  it("starts empty", () => assert.equal(session.runs.length, 0));

  it("records a run", () => {
    session.runs.push(104);
    assert.deepEqual(session.runs, [104]);
  });

  it("is isolated from the previous test", () => {
    assert.equal(session.runs.length, 0);
  });
});

How it works

  1. beforeEach rebuilds state so tests stay independent.
  2. after is where a server or a temp directory goes away.
  3. Hooks are scoped to their describe block.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
583
Tokens
177
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 2 of 2 in Async & hooks, step 4 of 9 in Testing with node:test.

← Previous Next →