as you can see from the before image, out of the describe it is not called, but all the others are.
There's a reason or it doesn't work, that's it.
If I put it in describe it works.
import {
before,
beforeEach,
after,
afterEach,
describe,
it,
test,
} from "node:test";
import assert from "node:assert";
import { add, subtract } from "../index.js";
before(function () {
console.log("before");
});
beforeEach(function () {
console.log("beforeEach");
});
afterEach(function () {
console.log("afterEach");
});
after(function () {
console.log("after");
});
describe("Arithmetic Operations", () => {
it("should correctly add two numbers", () => {
const result = add(2, 3);
assert.strictEqual(result, 5);
});
it("should correctly subtract two numbers", () => {
const result = subtract(5, 3);
assert.strictEqual(result, 2);
});
});
This seems like a bug in the Node.js test runner, which isn't completely surprising given that you're using Node.js 18.17.1 and the test runner was only declared stable in Node.js 20.0.0.
With Node.js 18.17.1, I was able to consistently reproduce this behavior:
➜ nvm use 18.17.1
Now using node v18.17.1 (npm v9.6.7)
➜ node node.test.js
beforeEach
afterEach
beforeEach
afterEach
▶ Arithmetic Operations
✔ should correctly add two numbers (0.834959ms)
✔ should correctly subtract two numbers (0.168333ms)
▶ Arithmetic Operations (1.795125ms)
after
ℹ tests 2
ℹ suites 1
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 0.213542
However, once I switched to the latest Node.js version (22.3.0 at the time of writing), this code indeed works as expected:
➜ nvm use 22.3.0
Now using node v22.3.0 (npm v10.8.1)
➜ node node.test.js
before
beforeEach
afterEach
beforeEach
afterEach
after
▶ Arithmetic Operations
✔ should correctly add two numbers (0.517375ms)
✔ should correctly subtract two numbers (0.674292ms)
▶ Arithmetic Operations (1.538292ms)
ℹ tests 2
ℹ suites 1
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6.906708