QuickDevGuide

Home › Mocha JS Testing

Hooks: before, after, beforeEach, afterEach — Mocha JS Testing

Hooks set up and tear down state around tests. Hook Runs before once, before the first test in the describe beforeEach before every test in the block (and nested blocks) afterEach after every test — even failed ones after once, after the last test in the block Order with nesting Outer beforeEach runs before inner beforeEach; afterEach runs inner first. Hooks at the top level of a file (outside any describe) apply to all files — prefer root hook plugins (--require hooks.mjs exporting mochaHooks) for global setup. Rules of thumb Create fresh state in beforeEach so tests are independent and order-agnostic. Use before/after for expensive shared resources (a server, a DB connection). Don't use arrow functions if you need this (e.g. this.timeout(), this.currentTest).

Key Takeaways