Principle:Nightwatchjs Nightwatch Lifecycle Hooks
| Knowledge Sources | |
|---|---|
| Domains | Testing, Test_Lifecycle |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
A test lifecycle management pattern that executes setup and teardown logic at defined points before and after test execution.
Description
Lifecycle hooks provide insertion points for setup and teardown code around test execution. The four standard hooks are before (once before all tests), beforeEach (before each test), afterEach (after each test), and after (once after all tests). Hooks can be defined at two levels: globally (in the globals module, affecting all test suites) or locally (within a describe block, affecting only that suite).
This pattern solves the code duplication problem: common setup actions (launching browsers, seeding data, configuring state) are written once and executed automatically at the appropriate lifecycle stage.
Usage
Use lifecycle hooks when tests require shared setup (e.g., navigating to a base URL), shared teardown (e.g., closing the browser, cleaning up state), or cross-cutting concerns (e.g., logging, screenshots on failure).
Theoretical Basis
The hook execution order follows a deterministic sequence:
- Global before runs once before any test suite
- Local before runs once before the suite's tests
- For each test:
- Global beforeEach runs
- Local beforeEach runs
- Test body executes
- Local afterEach runs
- Global afterEach runs
- Local after runs once after all suite tests
- Global after runs once after all suites
Hooks support both synchronous and asynchronous execution via callback or async/await patterns.