Implementation:Nightwatchjs Nightwatch Namespaced Command Pattern
| Knowledge Sources | |
|---|---|
| Domains | Testing, Extensibility, Organization |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Pattern for creating namespaced custom commands in Nightwatch.js by placing command files in subdirectories of custom_commands_path.
Description
Placing a command module in a subdirectory within custom_commands_path automatically creates a namespace on the browser object. For example, custom-commands/angular/getElementsInList.js registers as browser.angular.getElementsInList(). The command itself follows the same interface as non-namespaced commands (object or class style).
Usage
Create subdirectories in the custom_commands_path for each namespace group. Place command files within those subdirectories.
Code Reference
Source Location
- Repository: nightwatch
- File: examples/custom-commands/angular/getElementsInList.js (lines 1-20)
Signature
// File: custom-commands/angular/getElementsInList.js
// Registered as: browser.angular.getElementsInList()
module.exports = class AngularCommand {
async command(listName: string, cb?: Function) -> Promise<any>
};
// Directory structure:
// custom-commands/
// strictClick.js → browser.strictClick()
// angular/
// getElementsInList.js → browser.angular.getElementsInList()
Import
// No import required - auto-loaded with namespace from directory structure
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| Subdirectory name | Directory | Yes | Becomes the namespace prefix on browser object |
| Command file | JS module | Yes | Command following standard interface |
Outputs
| Name | Type | Description |
|---|---|---|
| browser.namespace.commandName() | Function | Namespaced command accessible in tests |
Usage Examples
Angular Namespaced Command
// custom-commands/angular/getElementsInList.js
module.exports = class AngularCommand {
async command(listName, cb = function(r) { return r; }) {
return this.api.executeScript(function(listName) {
var elements = document.querySelectorAll(
'*[ng-repeat$="' + listName + '"]'
);
return elements || null;
}, [listName], async function(result) {
const cbResult = await cb(result);
return cbResult.value ? cbResult.value : cbResult;
});
}
};
// Usage in tests:
// browser.angular.getElementsInList('item in todoList');
Directory Structure Example
custom-commands/
strictClick.js # browser.strictClick(selector)
angular/
getElementsInList.js # browser.angular.getElementsInList(list)
auth/
loginAs.js # browser.auth.loginAs(user, pass)
logout.js # browser.auth.logout()