0
# Programmatic API
1
2
Programmatic client creation and test runner for integrating Nightwatch into custom applications and workflows.
3
4
## Capabilities
5
6
### Create Client
7
8
Creates a programmatic Nightwatch client with full configuration control.
9
10
```javascript { .api }
11
/**
12
* Create a programmatic Nightwatch client
13
* @param options - Configuration options for the client
14
* @returns Client instance with browser API and lifecycle methods
15
*/
16
Nightwatch.createClient(options: CreateClientOptions): NightwatchProgrammaticClient;
17
18
interface CreateClientOptions {
19
/** Run browser in headless mode */
20
headless?: boolean;
21
/** Suppress console output */
22
silent?: boolean;
23
/** Enable console output */
24
output?: boolean;
25
/** Use async command mode */
26
useAsync?: boolean;
27
/** Environment name to use */
28
env?: string;
29
/** Browser name (chrome, firefox, safari, edge) */
30
browserName?: string;
31
/** Path to configuration file */
32
config?: string;
33
/** Test timeout in milliseconds */
34
timeout?: number;
35
/** Run tests in parallel */
36
parallel?: boolean;
37
/** Global variables */
38
globals?: object;
39
/** Enable global APIs in test context */
40
enable_global_apis?: boolean;
41
/** Reporter configuration */
42
reporter?: object;
43
/** Enable Chrome DevTools */
44
devtools?: boolean;
45
/** Enable debug mode */
46
debug?: boolean;
47
/** Disable process exit listener */
48
disable_process_listener?: boolean;
49
/** Additional test settings */
50
test_settings?: object;
51
}
52
53
interface NightwatchProgrammaticClient {
54
/** Update browser capabilities */
55
updateCapabilities(value: object): void;
56
/** Run global before hook */
57
runGlobalBeforeHook(): Promise<void>;
58
/** Run global after hook */
59
runGlobalAfterHook(): Promise<void>;
60
/** Launch browser session */
61
launchBrowser(options?: LaunchOptions): Promise<NightwatchAPI>;
62
/** Clean up resources */
63
cleanup(): Promise<void>;
64
/** Client settings */
65
settings: NightwatchOptions;
66
/** Transport layer */
67
transport: Transport;
68
/** Internal client instance */
69
nightwatch_client: NightwatchClient;
70
}
71
```
72
73
**Usage Examples:**
74
75
```javascript
76
import Nightwatch from "nightwatch";
77
78
// Basic client creation
79
const client = Nightwatch.createClient({
80
headless: true,
81
silent: false,
82
browserName: "chrome"
83
});
84
85
// Launch browser and run commands
86
const browser = await client.launchBrowser();
87
await browser.url("https://example.com");
88
await browser.assert.titleContains("Example");
89
await client.cleanup();
90
91
// Advanced configuration
92
const advancedClient = Nightwatch.createClient({
93
headless: false,
94
env: "chrome",
95
devtools: true,
96
globals: {
97
myVariable: "test-value"
98
},
99
test_settings: {
100
screenshots: {
101
enabled: true,
102
path: "./screenshots"
103
}
104
}
105
});
106
```
107
108
### Run Tests
109
110
Programmatically execute test suites with full control over test sources and settings.
111
112
```javascript { .api }
113
/**
114
* Run tests programmatically
115
* @param testSource - Test files or patterns to run
116
* @param settings - Runtime settings and configuration
117
* @returns Promise resolving to test results
118
*/
119
Nightwatch.runTests(
120
testSource?: string | string[] | object,
121
settings?: object
122
): Promise<boolean>;
123
```
124
125
**Usage Examples:**
126
127
```javascript
128
import Nightwatch from "nightwatch";
129
130
// Run specific test file
131
const result = await Nightwatch.runTests("./tests/login.js");
132
133
// Run multiple test files
134
const multiResult = await Nightwatch.runTests([
135
"./tests/login.js",
136
"./tests/checkout.js"
137
]);
138
139
// Run with custom settings
140
const customResult = await Nightwatch.runTests("./tests/", {
141
output_folder: "./test-results",
142
reporter: ["json", "html"],
143
globals: {
144
baseUrl: "https://staging.example.com"
145
}
146
});
147
148
// Run tests from pattern with configuration
149
const patternResult = await Nightwatch.runTests({
150
_source: ["./tests/**/*.spec.js"],
151
env: "chrome",
152
timeout: 30000
153
});
154
```
155
156
### CLI Runner
157
158
Create and configure CLI runner instances for advanced test orchestration.
159
160
```javascript { .api }
161
/**
162
* Create CLI runner instance
163
* @param argv - Command-line arguments
164
* @returns CLI runner instance
165
*/
166
Nightwatch.CliRunner(argv?: object): CliRunner;
167
168
interface CliRunner {
169
/** Setup runner with settings */
170
setup(settings?: object): CliRunner;
171
/** Setup runner asynchronously */
172
setupAsync(settings?: object): Promise<CliRunner>;
173
/** Run the test suite */
174
runTests(): Promise<boolean>;
175
/** Get list of test files */
176
getTestsFiles(): Promise<string[]>;
177
/** Runner settings */
178
settings: NightwatchOptions;
179
/** Command-line arguments */
180
argv: object;
181
}
182
```
183
184
**Usage Examples:**
185
186
```javascript
187
import Nightwatch from "nightwatch";
188
189
// Basic CLI runner
190
const runner = Nightwatch.CliRunner({
191
_source: ["./tests/"],
192
env: "chrome"
193
});
194
195
await runner.setupAsync();
196
const success = await runner.runTests();
197
198
// Advanced runner configuration
199
const advancedRunner = Nightwatch.CliRunner({
200
config: "./nightwatch.conf.js",
201
env: "firefox",
202
parallel: true,
203
reporter: "json",
204
output_folder: "./results"
205
});
206
207
// Get test files list
208
const testFiles = await advancedRunner.getTestsFiles();
209
console.log("Found test files:", testFiles);
210
```
211
212
### Initialize Client
213
214
Initialize a simple Nightwatch client with minimal configuration.
215
216
```javascript { .api }
217
/**
218
* Initialize basic Nightwatch client
219
* @param opts - Basic initialization options
220
* @returns Initialized client instance
221
*/
222
Nightwatch.initClient(opts?: object): NightwatchClient;
223
```
224
225
**Usage Examples:**
226
227
```javascript
228
import Nightwatch from "nightwatch";
229
230
// Initialize with default settings
231
const client = Nightwatch.initClient();
232
233
// Initialize with custom options
234
const customClient = Nightwatch.initClient({
235
selenium: {
236
start_process: false,
237
host: "localhost",
238
port: 4444
239
},
240
webdriver: {
241
start_process: true,
242
server_path: "/usr/local/bin/chromedriver"
243
}
244
});
245
```
246
247
### Client Factory
248
249
Create raw Nightwatch client instances for advanced use cases.
250
251
```javascript { .api }
252
/**
253
* Create raw Nightwatch client
254
* @param settings - Client settings
255
* @param reporter - Reporter instance
256
* @param argv - Command-line arguments
257
* @param skipInit - Skip initialization
258
* @returns Raw client instance
259
*/
260
Nightwatch.client(
261
settings: object,
262
reporter?: object,
263
argv?: object,
264
skipInit?: boolean
265
): NightwatchClient;
266
```
267
268
## Error Handling
269
270
```javascript
271
import Nightwatch from "nightwatch";
272
273
try {
274
const client = Nightwatch.createClient({
275
browserName: "chrome",
276
headless: true
277
});
278
279
const browser = await client.launchBrowser();
280
await browser.url("https://example.com");
281
await browser.assert.titleContains("Expected");
282
283
} catch (error) {
284
console.error("Test failed:", error.message);
285
286
// Handle specific error types
287
if (error.name === "TimeoutError") {
288
console.error("Test timed out");
289
} else if (error.name === "AssertionError") {
290
console.error("Assertion failed:", error.actual, "vs", error.expected);
291
}
292
293
} finally {
294
await client.cleanup();
295
}
296
```
297
298
## Integration Examples
299
300
### Custom Test Runner
301
302
```javascript
303
import Nightwatch from "nightwatch";
304
305
class CustomTestRunner {
306
constructor(options = {}) {
307
this.client = Nightwatch.createClient({
308
headless: options.headless ?? true,
309
browserName: options.browser ?? "chrome",
310
silent: true
311
});
312
}
313
314
async runSuite(testFiles) {
315
const browser = await this.client.launchBrowser();
316
const results = [];
317
318
for (const testFile of testFiles) {
319
try {
320
const result = await this.runTestFile(browser, testFile);
321
results.push({ file: testFile, ...result });
322
} catch (error) {
323
results.push({ file: testFile, error: error.message });
324
}
325
}
326
327
await this.client.cleanup();
328
return results;
329
}
330
331
async runTestFile(browser, testFile) {
332
// Custom test execution logic
333
return { passed: true, duration: 1234 };
334
}
335
}
336
```
337
338
### CI/CD Integration
339
340
```javascript
341
import Nightwatch from "nightwatch";
342
343
async function runCIPipeline() {
344
const environments = ["chrome", "firefox", "safari"];
345
const results = {};
346
347
for (const env of environments) {
348
console.log(`Running tests on ${env}...`);
349
350
try {
351
const success = await Nightwatch.runTests("./tests/", {
352
env: env,
353
headless: true,
354
output_folder: `./results/${env}`,
355
reporter: ["json", "junit"]
356
});
357
358
results[env] = { success, timestamp: new Date().toISOString() };
359
360
} catch (error) {
361
results[env] = { success: false, error: error.message };
362
}
363
}
364
365
// Generate summary report
366
const totalTests = Object.keys(results).length;
367
const passedTests = Object.values(results).filter(r => r.success).length;
368
369
console.log(`Pipeline complete: ${passedTests}/${totalTests} environments passed`);
370
371
if (passedTests < totalTests) {
372
process.exit(1);
373
}
374
}
375
```