Node.js
Before and after
Learn before/beforeEach/afterEach hooks.
Hook concept
Functions that run before and after tests are called hooks. node:test has four hooks: before runs once before the group, after once after, beforeEach before every test, afterEach after every test.
Example: before(() => { db = open(); }) opens a database connection; after(() => { db.close(); }) closes it. beforeEach(() => { counter = 0; }) resets the counter before each test, so tests do not affect each other. Hooks inside a describe apply only to that group. Hook order: before → (for each test: beforeEach → test → afterEach) → after.
Difference between before and beforeEach
before and beforeEach are often confused. before runs ONCE before the group; it suits expensive setups (e.g. opening a database connection). beforeEach runs before every test; it gives each test a clean start (e.g. resetting variables).
Example: before(() => { setup(); }) and beforeEach(() => { data = []; }). after and afterEach work similarly afterward. Placing hooks at the top of a describe improves readability: first setup, then tests. If a hook throws, tests in that group are skipped.
Exercise Connect hooks with a test
Import test, before and after from node:test. Define let state = "empty";. Add before(() => { state = "ready"; }) and after(() => { state = "done"; }). Write test("test", () => {}). Print with console.log("Hooks set, state: " + state).
Show example solution
const { test, before, after } = require("node:test");
let state = "empty";
before(() => { state = "ready"; });
after(() => { state = "done"; });
test("test", () => {});
console.log("Hooks set, state: " + state);
Test yourself
-
When does beforeEach run?
beforeEach(() => { /* ... */ });
- Before each test
- Once before the group
- Her testten sonra
- Only after a failed test
Show answer
Before each test — beforeEach runs before every test.
-
Match each hook to its timing
- before
- Once before the group
- after
- Once after the group
- beforeEach
- Before every test
- afterEach
- After every test
-
Complete the beforeEach call
beforeEach(() => { ____ = 0; });
Show answer
beforeEach(() => { sayaç = 0; });
Next lesson: Mock