CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webdriverio

Next-gen browser and mobile automation test framework for Node.js

Pending
Overview
Eval results
Files

testing-utilities.mddocs/

Testing Utilities

Built-in testing, debugging, and performance utilities including network mocking, CPU/network throttling, interactive debugging, and browser integration tools.

Capabilities

Network Mocking

Mock network requests and responses for testing scenarios.

/**
 * Create a network mock for intercepting requests
 * @param url - URL pattern to mock (string or RegExp)
 * @param options - Mock configuration options
 * @returns Promise resolving to a Mock instance
 */
mock(url: string, options?: object): Promise<WebdriverIO.Mock>;

/**
 * Restore all network mocks to their original state
 * @returns Promise that resolves when all mocks are restored
 */
mockRestoreAll(): Promise<void>;

/**
 * Clear all network mock call history and state
 * @returns Promise that resolves when all mocks are cleared
 */
mockClearAll(): Promise<void>;

interface WebdriverIO.Mock {
  calls: MockCall[];
  restore(): void;
  clear(): void;
  respond(response: MockResponse): void;
  respondOnce(response: MockResponse): void;
  abort(errorCode?: string): void;
  abortOnce(errorCode?: string): void;
}

interface MockCall {
  url: string;
  method: string;
  headers: object;
  body: string;
  timestamp: number;
}

interface MockResponse {
  statusCode?: number;
  headers?: object;
  body?: string | object;
  delay?: number;
}

Usage Examples:

// Mock API endpoint
const apiMock = await browser.mock('**/api/users');
apiMock.respond({
  statusCode: 200,
  body: {
    users: [
      { id: 1, name: 'John Doe' },
      { id: 2, name: 'Jane Smith' }
    ]
  }
});

// Mock with delay
const slowApiMock = await browser.mock('**/api/slow-endpoint');
slowApiMock.respond({
  statusCode: 200,
  body: { message: 'Success' },
  delay: 3000
});

// Mock error responses
const errorMock = await browser.mock('**/api/error');
errorMock.respond({
  statusCode: 500,
  body: { error: 'Internal Server Error' }
});

// Inspect mock calls
await browser.url('/test-page');
console.log(apiMock.calls.length); // Number of intercepted calls
console.log(apiMock.calls[0].body); // Request body of first call

// Clean up mocks
await browser.mockRestoreAll();

Performance Testing

Tools for simulating various performance conditions and constraints.

/**
 * Throttle CPU performance
 * @param rate - CPU throttling rate (1 = no throttling, 4 = 4x slower)
 * @returns Promise that resolves when throttling is applied
 */
throttleCPU(rate: number): Promise<void>;

/**
 * Apply network throttling conditions
 * @param conditions - Network throttling configuration
 * @returns Promise that resolves when throttling is applied
 */
throttleNetwork(conditions: object): Promise<void>;

/**
 * Apply general throttling conditions (legacy method)
 * @param condition - Throttling condition name or configuration
 * @returns Promise that resolves when throttling is applied
 */
throttle(condition: string): Promise<void>;

Usage Examples:

// Throttle CPU to simulate slower devices
await browser.throttleCPU(4); // 4x slower CPU

// Apply network throttling for 3G simulation
await browser.throttleNetwork({
  offline: false,
  downloadThroughput: 1.5 * 1024 * 1024 / 8, // 1.5 Mbps
  uploadThroughput: 750 * 1024 / 8, // 750 Kbps
  latency: 150 // 150ms latency
});

// Use predefined throttling profiles
await browser.throttle('Regular 3G');
await browser.throttle('Good 3G');
await browser.throttle('Slow 3G');

// Disable throttling
await browser.throttleNetwork({ offline: false });
await browser.throttleCPU(1);

Debugging and Development

Interactive debugging and development assistance tools.

/**
 * Start an interactive debugging session with REPL
 * @returns Promise that resolves when debugging session ends
 */
debug(): Promise<void>;

/**
 * Pause execution for a specified duration
 * @param milliseconds - Duration to pause in milliseconds
 * @returns Promise that resolves after the pause
 */
pause(milliseconds: number): Promise<void>;

/**
 * Add an initialization script that runs before page load
 * @param script - JavaScript function or string to execute
 * @returns Promise resolving to InitScript object
 */
addInitScript(script: Function | string): Promise<InitScript>;

interface InitScript {
  id: string;
  source: string;
}

Usage Examples:

// Start interactive debugging
await browser.url('https://example.com');
await browser.debug(); // Opens REPL for interactive testing

// Add strategic pauses for observation
await browser.pause(2000); // Wait 2 seconds

// Add initialization script
await browser.addInitScript(() => {
  // This runs before each page load
  window.testMode = true;
  console.log('Test mode enabled');
});

// Add initialization script as string
await browser.addInitScript(`
  window.customTracker = {
    events: [],
    track: function(event) {
      this.events.push({ event: event, timestamp: Date.now() });
    }
  };
`);

Browser Integration

Tools for integrating with browser-specific features and debugging tools.

/**
 * Get access to the underlying Puppeteer browser instance (Chrome/Edge only)
 * @returns Promise resolving to Puppeteer browser instance
 */
getPuppeteer(): Promise<PuppeteerBrowser>;

/**
 * Emulate a specific device with predefined characteristics
 * @param device - Device configuration object
 * @returns Promise that resolves when device emulation is applied
 */
emulate(device: object): Promise<void>;

Usage Examples:

// Access Puppeteer for advanced Chrome features
const puppeteerBrowser = await browser.getPuppeteer();
const pages = await puppeteerBrowser.pages();
const page = pages[0];

// Use Puppeteer API directly
await page.coverage.startJSCoverage();
await browser.url('https://example.com');
const coverage = await page.coverage.stopJSCoverage();

// Emulate mobile device
await browser.emulate({
  name: 'iPhone 12',
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
  viewport: {
    width: 390,
    height: 844,
    deviceScaleFactor: 3,
    isMobile: true,
    hasTouch: true
  }
});

// Emulate desktop device
await browser.emulate({
  name: 'Desktop',
  viewport: {
    width: 1920,
    height: 1080,
    deviceScaleFactor: 1,
    isMobile: false,
    hasTouch: false
  }
});

Wait Utilities

Advanced waiting and synchronization utilities for robust test execution.

/**
 * Wait until a custom condition is met
 * @param condition - Function that returns true when condition is satisfied
 * @param options - Wait configuration options
 * @returns Promise resolving to the condition function's return value
 */
waitUntil(condition: Function, options?: object): Promise<any>;

interface WaitOptions {
  timeout?: number;
  timeoutMsg?: string;
  interval?: number;
}

Usage Examples:

// Wait for element to appear
await browser.waitUntil(async () => {
  const element = await browser.$('#dynamic-element');
  return await element.isExisting();
}, {
  timeout: 10000,
  timeoutMsg: 'Dynamic element never appeared'
});

// Wait for API data to load
await browser.waitUntil(async () => {
  const result = await browser.execute(() => {
    return window.apiDataLoaded === true;
  });
  return result;
}, {
  timeout: 15000,
  interval: 500
});

// Wait for complex condition
await browser.waitUntil(async () => {
  const elements = await browser.$$('.list-item');
  return elements.length >= 5;
}, {
  timeout: 20000,
  timeoutMsg: 'Expected at least 5 list items to be present'
});

Test Automation Helpers

Utility functions specifically designed for test automation workflows.

/**
 * Set timeout values for various WebDriver operations
 * @param timeouts - Timeout configuration object
 * @returns Promise that resolves when timeouts are configured
 */
setTimeout(timeouts: object): Promise<void>;

/**
 * Call a function with the browser instance as context
 * @param callback - Function to execute with browser context
 * @returns Promise resolving to the callback's return value
 */
call(callback: Function): Promise<any>;

Usage Examples:

// Configure various timeouts
await browser.setTimeout({
  implicit: 5000,        // Element finding timeout
  pageLoad: 30000,       // Page load timeout
  script: 15000          // JavaScript execution timeout
});

// Execute complex test logic with browser context
const testResults = await browser.call(async function() {
  // 'this' refers to the browser instance
  await this.url('https://example.com/form');
  
  const form = await this.$('#contact-form');
  await form.$('#name').setValue('Test User');
  await form.$('#email').setValue('test@example.com');
  await form.$('#submit').click();
  
  const success = await this.$('.success-message');
  const isVisible = await success.waitForDisplayed({ timeout: 5000 });
  
  return {
    formSubmitted: true,
    successVisible: isVisible,
    currentUrl: await this.getUrl()
  };
});

console.log(testResults);

Environment Detection

Utilities for detecting and adapting to different execution environments.

// Environment detection utilities (typically used internally)
interface EnvironmentInfo {
  isNode: boolean;
  isBrowser: boolean;
  platform: string;
  capabilities: object;
}

These utilities help WebdriverIO adapt its behavior based on whether it's running in Node.js or browser environments, and what capabilities are available in the current WebDriver session.

Install with Tessl CLI

npx tessl i tessl/npm-webdriverio

docs

browser-control.md

dialog-handling.md

element-interaction.md

element-selection.md

index.md

mobile-automation.md

session-management.md

testing-utilities.md

tile.json