CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nightwatch

Easy to use Node.js based end-to-end testing solution for web applications using the W3C WebDriver API.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

programmatic-api.mddocs/

Programmatic API

Programmatic client creation and test runner for integrating Nightwatch into custom applications and workflows.

Capabilities

Create Client

Creates a programmatic Nightwatch client with full configuration control.

/**
 * Create a programmatic Nightwatch client
 * @param options - Configuration options for the client
 * @returns Client instance with browser API and lifecycle methods
 */
Nightwatch.createClient(options: CreateClientOptions): NightwatchProgrammaticClient;

interface CreateClientOptions {
  /** Run browser in headless mode */
  headless?: boolean;
  /** Suppress console output */
  silent?: boolean;
  /** Enable console output */
  output?: boolean;
  /** Use async command mode */
  useAsync?: boolean;
  /** Environment name to use */
  env?: string;
  /** Browser name (chrome, firefox, safari, edge) */
  browserName?: string;
  /** Path to configuration file */
  config?: string;
  /** Test timeout in milliseconds */
  timeout?: number;
  /** Run tests in parallel */
  parallel?: boolean;
  /** Global variables */
  globals?: object;
  /** Enable global APIs in test context */
  enable_global_apis?: boolean;
  /** Reporter configuration */
  reporter?: object;
  /** Enable Chrome DevTools */
  devtools?: boolean;
  /** Enable debug mode */
  debug?: boolean;
  /** Disable process exit listener */
  disable_process_listener?: boolean;
  /** Additional test settings */
  test_settings?: object;
}

interface NightwatchProgrammaticClient {
  /** Update browser capabilities */
  updateCapabilities(value: object): void;
  /** Run global before hook */
  runGlobalBeforeHook(): Promise<void>;
  /** Run global after hook */
  runGlobalAfterHook(): Promise<void>;
  /** Launch browser session */
  launchBrowser(options?: LaunchOptions): Promise<NightwatchAPI>;
  /** Clean up resources */
  cleanup(): Promise<void>;
  /** Client settings */
  settings: NightwatchOptions;
  /** Transport layer */
  transport: Transport;
  /** Internal client instance */
  nightwatch_client: NightwatchClient;
}

Usage Examples:

import Nightwatch from "nightwatch";

// Basic client creation
const client = Nightwatch.createClient({
  headless: true,
  silent: false,
  browserName: "chrome"
});

// Launch browser and run commands
const browser = await client.launchBrowser();
await browser.url("https://example.com");
await browser.assert.titleContains("Example");
await client.cleanup();

// Advanced configuration
const advancedClient = Nightwatch.createClient({
  headless: false,
  env: "chrome",
  devtools: true,
  globals: {
    myVariable: "test-value"
  },
  test_settings: {
    screenshots: {
      enabled: true,
      path: "./screenshots"
    }
  }
});

Run Tests

Programmatically execute test suites with full control over test sources and settings.

/**
 * Run tests programmatically
 * @param testSource - Test files or patterns to run
 * @param settings - Runtime settings and configuration
 * @returns Promise resolving to test results
 */
Nightwatch.runTests(
  testSource?: string | string[] | object,
  settings?: object
): Promise<boolean>;

Usage Examples:

import Nightwatch from "nightwatch";

// Run specific test file
const result = await Nightwatch.runTests("./tests/login.js");

// Run multiple test files
const multiResult = await Nightwatch.runTests([
  "./tests/login.js",
  "./tests/checkout.js"
]);

// Run with custom settings
const customResult = await Nightwatch.runTests("./tests/", {
  output_folder: "./test-results",
  reporter: ["json", "html"],
  globals: {
    baseUrl: "https://staging.example.com"
  }
});

// Run tests from pattern with configuration
const patternResult = await Nightwatch.runTests({
  _source: ["./tests/**/*.spec.js"],
  env: "chrome",
  timeout: 30000
});

CLI Runner

Create and configure CLI runner instances for advanced test orchestration.

/**
 * Create CLI runner instance
 * @param argv - Command-line arguments
 * @returns CLI runner instance
 */
Nightwatch.CliRunner(argv?: object): CliRunner;

interface CliRunner {
  /** Setup runner with settings */
  setup(settings?: object): CliRunner;
  /** Setup runner asynchronously */
  setupAsync(settings?: object): Promise<CliRunner>;
  /** Run the test suite */
  runTests(): Promise<boolean>;
  /** Get list of test files */
  getTestsFiles(): Promise<string[]>;
  /** Runner settings */
  settings: NightwatchOptions;
  /** Command-line arguments */
  argv: object;
}

Usage Examples:

import Nightwatch from "nightwatch";

// Basic CLI runner
const runner = Nightwatch.CliRunner({
  _source: ["./tests/"],
  env: "chrome"
});

await runner.setupAsync();
const success = await runner.runTests();

// Advanced runner configuration
const advancedRunner = Nightwatch.CliRunner({
  config: "./nightwatch.conf.js",
  env: "firefox",
  parallel: true,
  reporter: "json",
  output_folder: "./results"
});

// Get test files list
const testFiles = await advancedRunner.getTestsFiles();
console.log("Found test files:", testFiles);

Initialize Client

Initialize a simple Nightwatch client with minimal configuration.

/**
 * Initialize basic Nightwatch client
 * @param opts - Basic initialization options
 * @returns Initialized client instance
 */
Nightwatch.initClient(opts?: object): NightwatchClient;

Usage Examples:

import Nightwatch from "nightwatch";

// Initialize with default settings
const client = Nightwatch.initClient();

// Initialize with custom options
const customClient = Nightwatch.initClient({
  selenium: {
    start_process: false,
    host: "localhost",
    port: 4444
  },
  webdriver: {
    start_process: true,
    server_path: "/usr/local/bin/chromedriver"
  }
});

Client Factory

Create raw Nightwatch client instances for advanced use cases.

/**
 * Create raw Nightwatch client
 * @param settings - Client settings
 * @param reporter - Reporter instance
 * @param argv - Command-line arguments
 * @param skipInit - Skip initialization
 * @returns Raw client instance
 */
Nightwatch.client(
  settings: object,
  reporter?: object,
  argv?: object,
  skipInit?: boolean
): NightwatchClient;

Error Handling

import Nightwatch from "nightwatch";

try {
  const client = Nightwatch.createClient({
    browserName: "chrome",
    headless: true
  });
  
  const browser = await client.launchBrowser();
  await browser.url("https://example.com");
  await browser.assert.titleContains("Expected");
  
} catch (error) {
  console.error("Test failed:", error.message);
  
  // Handle specific error types
  if (error.name === "TimeoutError") {
    console.error("Test timed out");
  } else if (error.name === "AssertionError") {
    console.error("Assertion failed:", error.actual, "vs", error.expected);
  }
  
} finally {
  await client.cleanup();
}

Integration Examples

Custom Test Runner

import Nightwatch from "nightwatch";

class CustomTestRunner {
  constructor(options = {}) {
    this.client = Nightwatch.createClient({
      headless: options.headless ?? true,
      browserName: options.browser ?? "chrome",
      silent: true
    });
  }
  
  async runSuite(testFiles) {
    const browser = await this.client.launchBrowser();
    const results = [];
    
    for (const testFile of testFiles) {
      try {
        const result = await this.runTestFile(browser, testFile);
        results.push({ file: testFile, ...result });
      } catch (error) {
        results.push({ file: testFile, error: error.message });
      }
    }
    
    await this.client.cleanup();
    return results;
  }
  
  async runTestFile(browser, testFile) {
    // Custom test execution logic
    return { passed: true, duration: 1234 };
  }
}

CI/CD Integration

import Nightwatch from "nightwatch";

async function runCIPipeline() {
  const environments = ["chrome", "firefox", "safari"];
  const results = {};
  
  for (const env of environments) {
    console.log(`Running tests on ${env}...`);
    
    try {
      const success = await Nightwatch.runTests("./tests/", {
        env: env,
        headless: true,
        output_folder: `./results/${env}`,
        reporter: ["json", "junit"]
      });
      
      results[env] = { success, timestamp: new Date().toISOString() };
      
    } catch (error) {
      results[env] = { success: false, error: error.message };
    }
  }
  
  // Generate summary report
  const totalTests = Object.keys(results).length;
  const passedTests = Object.values(results).filter(r => r.success).length;
  
  console.log(`Pipeline complete: ${passedTests}/${totalTests} environments passed`);
  
  if (passedTests < totalTests) {
    process.exit(1);
  }
}

docs

advanced-features.md

assertions-expectations.md

browser-control.md

element-interaction.md

index.md

modern-element-api.md

page-object-model.md

programmatic-api.md

protocol-commands.md

tile.json