Implementation:Nightwatchjs Nightwatch Lifecycle Hooks Interface
| Knowledge Sources | |
|---|---|
| Domains | Testing, Test_Lifecycle |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Interface specification for defining lifecycle hooks (before, beforeEach, after, afterEach) in Nightwatch.js test suites and global modules.
Description
Lifecycle hooks are user-defined functions placed in the globals module or within describe blocks. Global hooks are defined in the file specified by globals_path in the Nightwatch configuration. Test-level hooks are defined inside describe blocks. Each hook receives the browser instance and/or a callback function that must be invoked to signal completion for async operations.
Usage
Define hooks in the globals module for cross-suite setup/teardown, or within describe blocks for suite-specific logic. Always call the callback (cb) in async hooks to prevent timeout errors.
Code Reference
Source Location
- Repository: nightwatch
- File: examples/globalsModule.js (lines 46-66)
- File: examples/tests/ecosia.js (lines 3-5, 19)
Signature
// Global hooks (in globals module)
before(cb: Function) -> void
beforeEach(browser: NightwatchBrowser, cb: Function) -> void
after(cb: Function) -> void
afterEach(browser: NightwatchBrowser, cb: Function) -> void
// Test-level hooks (in describe blocks)
before(browser: NightwatchBrowser) -> void | Promise
beforeEach(browser: NightwatchBrowser) -> void | Promise
after(browser: NightwatchBrowser) -> void | Promise
afterEach(browser: NightwatchBrowser) -> void | Promise
Import
// No import required - hooks are defined as properties in globals module
// or within describe blocks
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| browser | NightwatchBrowser | No (global before/after) | Browser API instance for performing actions |
| cb | Function | Yes (global hooks) | Callback that must be called to signal hook completion |
Outputs
| Name | Type | Description |
|---|---|---|
| Setup/teardown side effects | void | Actions performed (navigation, cleanup, logging) |
| cb() invocation | void | Signals hook completion to the test runner |
Usage Examples
Global Hooks
// globals.js
module.exports = {
before(cb) {
console.log('Global setup');
cb();
},
beforeEach(browser, cb) {
console.log('Before each test');
cb();
},
after(cb) {
console.log('Global teardown');
cb();
},
afterEach(browser, cb) {
browser.perform(function() {
console.log('After each test');
cb();
});
}
};
Test-Level Hooks
describe('My Test Suite', function() {
before(browser => {
browser.navigateTo('https://example.com');
});
after(browser => browser.end());
it('test case', function(browser) {
browser.assert.titleContains('Example');
});
});