Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Principle:Nightwatchjs Nightwatch Lifecycle Hooks

From Leeroopedia
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:

  1. Global before runs once before any test suite
  2. Local before runs once before the suite's tests
  3. For each test:
    1. Global beforeEach runs
    2. Local beforeEach runs
    3. Test body executes
    4. Local afterEach runs
    5. Global afterEach runs
  4. Local after runs once after all suite tests
  5. Global after runs once after all suites

Hooks support both synchronous and asynchronous execution via callback or async/await patterns.

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment