Before and after
- Node.js course
- Intermediate
- Lesson 85/116
- 5 min
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.
Practice 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).
Starter code
// Import test, before and after
// write here
// Define state
let state = "empty";
// Add before and after hooks
// write here
// Write a test
// write here
// Print "Hooks set, state: ..."
// write hereSample 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);Expected output
Kancalar kuruldu, durum: hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does beforeEach run?
beforeEach(() => { /* ... */ });- Before each test Correct answer
- Once before the group
- Her testten sonra
- Only after a failed test
Explanation: beforeEach runs before every test.
2 Match each hook to its timing
| Term | Meaning |
|---|---|
before |
Once before the group |
after |
Once after the group |
beforeEach |
Before every test |
afterEach |
After every test |
3 Complete the beforeEach call
beforeEach(() => { ____ = 0; });
beforeEach(() => { sayaç = 0; });
Explanation: The counter is reset before each test.