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

advanced-features.mddocs/

Advanced Features

Advanced testing capabilities including performance monitoring, accessibility testing, mobile support, logging, and network operations.

Capabilities

Performance Monitoring

Monitor and capture browser performance metrics for performance testing.

/**
 * Take memory heap snapshot
 * @returns Promise resolving when snapshot captured
 */
browser.takeHeapSnapshot();

/**
 * Enable performance metrics collection
 * @returns Promise resolving when metrics enabled
 */
browser.enablePerformanceMetrics();

/**
 * Get collected performance metrics
 * @returns Promise resolving with performance data
 */
browser.getPerformanceMetrics(): Promise<PerformanceMetrics>;

/**
 * Performance metrics interface
 */
interface PerformanceMetrics {
  Timestamp: number;
  Documents: number;
  Frames: number;
  JSEventListeners: number;
  Nodes: number;
  LayoutCount: number;
  RecalcStyleCount: number;
  LayoutDuration: number;
  RecalcStyleDuration: number;
  ScriptDuration: number;
  TaskDuration: number;
}

Usage Examples:

// Monitor page performance
browser
  .url('https://example.com')
  .enablePerformanceMetrics()
  .waitForElementVisible('body', 5000)
  .getPerformanceMetrics()
  .then(metrics => {
    console.log('Layout count:', metrics.LayoutCount);
    console.log('Script duration:', metrics.ScriptDuration);
  })
  .takeHeapSnapshot();

Accessibility Testing

Integrate accessibility testing using the aXe accessibility engine.

/**
 * Inject aXe accessibility testing library into page
 * @returns Promise resolving when aXe injected
 */
browser.axeInject();

/**
 * Run accessibility audit tests
 * @param options - aXe testing options
 * @returns Promise resolving with accessibility results
 */
browser.axeRun(options?: AxeOptions): Promise<AxeResults>;

/**
 * aXe testing options interface
 */
interface AxeOptions {
  // CSS selector or elements to include/exclude
  include?: string[] | Element[];
  exclude?: string[] | Element[];
  
  // Accessibility rules to run
  rules?: Record<string, {enabled: boolean}>;
  
  // Result types to return
  resultTypes?: ('violations' | 'incomplete' | 'passes' | 'inapplicable')[];
  
  // Tags to filter rules
  tags?: string[];
}

/**
 * aXe results interface
 */
interface AxeResults {
  violations: AxeViolation[];
  passes: AxeResult[];
  incomplete: AxeResult[];
  inapplicable: AxeResult[];
  timestamp: string;
  url: string;
}

/**
 * aXe violation interface
 */
interface AxeViolation {
  id: string;
  impact: 'minor' | 'moderate' | 'serious' | 'critical';
  description: string;
  help: string;
  helpUrl: string;
  nodes: AxeNode[];
}

Usage Examples:

// Basic accessibility testing
browser
  .url('https://example.com')
  .axeInject()
  .axeRun()
  .then(results => {
    if (results.violations.length > 0) {
      console.log('Accessibility violations found:', results.violations.length);
      results.violations.forEach(violation => {
        console.log(`${violation.impact}: ${violation.description}`);
      });
    }
  });

// Targeted accessibility testing
browser
  .url('https://example.com/form')
  .axeInject()
  .axeRun({
    include: ['#main-form'],
    exclude: ['.advertisement'],
    tags: ['wcag2a', 'wcag21aa'],
    rules: {
      'color-contrast': { enabled: true },
      'keyboard-navigation': { enabled: true }
    }
  })
  .then(results => {
    console.log('Form accessibility check:', results.violations.length, 'violations');
  });

Mobile Testing Support

Detect and control mobile platform capabilities.

/**
 * Check if running on iOS platform
 * @returns Boolean indicating iOS platform
 */
browser.isIOS(): boolean;

/**
 * Check if running on Android platform  
 * @returns Boolean indicating Android platform
 */
browser.isAndroid(): boolean;

/**
 * Check if running on mobile platform (iOS or Android)
 * @returns Boolean indicating mobile platform
 */
browser.isMobile(): boolean;

/**
 * Set device dimensions for mobile testing
 * @param width - Device width in pixels
 * @param height - Device height in pixels
 * @returns Promise resolving when dimensions set
 */
browser.setDeviceDimensions(width: number, height: number);

/**
 * Set GPS coordinates for location testing
 * @param latitude - Latitude coordinate
 * @param longitude - Longitude coordinate
 * @returns Promise resolving when location set
 */
browser.setGeolocation(latitude: number, longitude: number);

Usage Examples:

// Platform-specific testing
if (browser.isMobile()) {
  console.log('Running on mobile platform');
  
  if (browser.isIOS()) {
    console.log('iOS-specific testing');
    browser.setDeviceDimensions(375, 812); // iPhone X dimensions
  } else if (browser.isAndroid()) {
    console.log('Android-specific testing');
    browser.setDeviceDimensions(360, 640); // Android dimensions
  }
  
  // Set location for mobile testing
  browser.setGeolocation(37.7749, -122.4194); // San Francisco
}

// Responsive testing
browser
  .url('https://example.com')
  .setDeviceDimensions(320, 568) // Mobile
  .assert.visible('.mobile-menu')
  .setDeviceDimensions(1024, 768) // Tablet
  .assert.visible('.tablet-layout')
  .resizeWindow(1920, 1080) // Desktop
  .assert.visible('.desktop-header');

Browser Logging

Access and manage browser logs for debugging and monitoring.

/**
 * Get browser logs by type
 * @param type - Log type ('browser', 'driver', 'client', 'server')
 * @returns Promise resolving with log entries
 */
browser.getLog(type: LogType): Promise<LogEntry[]>;

/**
 * Get available log types
 * @returns Promise resolving with array of log types
 */
browser.getLogTypes(): Promise<LogType[]>;

/**
 * Check if specific log type is available
 * @param type - Log type to check
 * @returns Promise resolving with availability boolean
 */
browser.isLogAvailable(type: LogType): Promise<boolean>;

/**
 * Log type options
 */
type LogType = 'browser' | 'driver' | 'client' | 'server' | 'performance';

/**
 * Log entry interface
 */
interface LogEntry {
  level: 'SEVERE' | 'WARNING' | 'INFO' | 'DEBUG';
  message: string;
  timestamp: number;
  source: string;
}

Usage Examples:

// Check browser console logs
browser
  .url('https://example.com')
  .getLogTypes()
  .then(types => {
    console.log('Available log types:', types);
  })
  .getLog('browser')
  .then(logs => {
    logs.forEach(log => {
      if (log.level === 'SEVERE') {
        console.log('Browser error:', log.message);
      }
    });
  });

// Monitor performance logs
browser
  .isLogAvailable('performance')
  .then(available => {
    if (available) {
      return browser.getLog('performance');
    }
  })
  .then(perfLogs => {
    if (perfLogs) {
      console.log('Performance entries:', perfLogs.length);
    }
  });

Authentication

Handle HTTP authentication for secured applications.

/**
 * Register HTTP basic authentication credentials
 * @param username - Username for authentication
 * @param password - Password for authentication
 * @returns Promise resolving when credentials registered
 */
browser.registerBasicAuth(username: string, password: string);

Usage Examples:

// Set up basic authentication
browser
  .registerBasicAuth('testuser', 'secret123')
  .url('https://secured.example.com')
  .waitForElementVisible('body', 5000)
  .assert.titleContains('Secured Area');

Network Operations

Monitor and control network behavior for testing network conditions.

/**
 * Mock HTTP responses for testing
 * @param url - URL pattern to mock
 * @param response - Mock response configuration
 * @returns Promise resolving when mock configured
 */
browser.mockResponse(url: string | RegExp, response: MockResponse);

/**
 * Set network conditions for testing
 * @param conditions - Network condition parameters
 * @returns Promise resolving when conditions set
 */
browser.setConditions(conditions: NetworkConditions);

/**
 * Capture network requests for analysis
 * @param callback - Function to handle captured requests
 * @returns Promise resolving when capture configured
 */
browser.captureRequests(callback: (request: NetworkRequest) => void);

/**
 * Mock response configuration
 */
interface MockResponse {
  status: number;
  headers?: Record<string, string>;
  body?: string | object;
  delay?: number;
}

/**
 * Network conditions configuration
 */
interface NetworkConditions {
  offline: boolean;
  downloadThroughput: number; // bytes/sec
  uploadThroughput: number;   // bytes/sec
  latency: number;            // milliseconds
}

/**
 * Network request information
 */
interface NetworkRequest {
  url: string;
  method: string;
  headers: Record<string, string>;
  body?: string;
  timestamp: number;
}

Usage Examples:

// Mock API responses
browser
  .mockResponse('/api/users', {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
    body: { users: [{ id: 1, name: 'Test User' }] }
  })
  .url('https://example.com/users')
  .waitForElementVisible('.user-list', 5000);

// Test slow network conditions
browser
  .setConditions({
    offline: false,
    downloadThroughput: 1024 * 1024, // 1MB/s
    uploadThroughput: 512 * 1024,    // 512KB/s
    latency: 100                     // 100ms
  })
  .url('https://example.com')
  .waitForElementVisible('body', 10000);

// Capture and analyze requests
browser
  .captureRequests(request => {
    console.log(`${request.method} ${request.url}`);
    if (request.url.includes('/api/')) {
      console.log('API request captured:', request);
    }
  })
  .url('https://example.com')
  .click('#load-data-button');

Debug and Development Tools

Tools for debugging tests and development workflow.

/**
 * Enter interactive debug mode
 * @returns Promise resolving when debug session ends
 */
browser.debug();

/**
 * Pause test execution for specified duration
 * @param ms - Milliseconds to pause
 * @returns Promise resolving after pause
 */
browser.pause(ms: number);

Usage Examples:

// Debug test execution
browser
  .url('https://example.com')
  .debug() // Pauses here for manual inspection
  .click('#submit-button')
  .pause(2000) // Wait 2 seconds
  .assert.visible('#success-message');

Screenshot and Snapshot Utilities

Enhanced screenshot and DOM snapshot capabilities.

/**
 * Capture and save screenshot with custom options
 * @param filename - Path to save screenshot
 * @param options - Screenshot options
 * @returns Promise resolving when screenshot saved
 */
browser.saveScreenshot(filename: string, options?: ScreenshotOptions);

/**
 * Save DOM snapshot to file
 * @param filename - Path to save snapshot
 * @param options - Snapshot options
 * @returns Promise resolving when snapshot saved
 */
browser.saveSnapshot(filename: string, options?: SnapshotOptions);

/**
 * Screenshot options
 */
interface ScreenshotOptions {
  // Element to screenshot (default: full page)
  element?: string;
  
  // Include element padding
  padding?: number;
  
  // Hide elements before screenshot
  hideElements?: string[];
}

/**
 * Snapshot options
 */
interface SnapshotOptions {
  // Include inline styles
  includeStyles?: boolean;
  
  // Include script tags
  includeScripts?: boolean;
  
  // Pretty print HTML
  prettyPrint?: boolean;
}

Usage Examples:

// Enhanced screenshots
browser
  .url('https://example.com')
  .saveScreenshot('./screenshots/full-page.png')
  .saveScreenshot('./screenshots/header-only.png', {
    element: '#header',
    padding: 10,
    hideElements: ['.advertisement', '.popup']
  });

// DOM snapshots with options
browser
  .saveSnapshot('./snapshots/page-state.html', {
    includeStyles: true,
    includeScripts: false,
    prettyPrint: true
  });

Global Browser Detection

Utility methods for detecting browser capabilities and versions.

/**
 * Check if current browser is Chrome
 * @returns Boolean indicating Chrome browser
 */
browser.isChrome(): boolean;

/**
 * Check if current browser is Firefox
 * @returns Boolean indicating Firefox browser  
 */
browser.isFirefox(): boolean;

/**
 * Check if current browser is Safari
 * @returns Boolean indicating Safari browser
 */
browser.isSafari(): boolean;

/**
 * Check if current browser is Edge
 * @returns Boolean indicating Edge browser
 */
browser.isEdge(): boolean;

/**
 * Check if current browser is Internet Explorer
 * @returns Boolean indicating IE browser
 */
browser.isInternetExplorer(): boolean;

Usage Examples:

// Browser-specific testing
if (browser.isChrome()) {
  console.log('Running Chrome-specific tests');
  browser.enablePerformanceMetrics();
} else if (browser.isFirefox()) {
  console.log('Running Firefox-specific tests');
  // Firefox-specific configuration
} else if (browser.isSafari()) {
  console.log('Running Safari-specific tests');
  // Safari-specific workarounds
}

// Cross-browser feature detection
const features = {
  performanceMetrics: browser.isChrome(),
  advancedDebugging: browser.isChrome() || browser.isFirefox(),
  touchEvents: browser.isMobile()
};

console.log('Available features:', features);

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