Previous: WebDriverIO Fundamentals Next: Asynchronous Testing with WebDriverIO

Module 2: Selectors and Element Interactions

Learning Objectives

2.1 Selector Strategies

CSS Selectors

CSS selectors are the most commonly used method for locating elements in WebDriverIO.

// Basic CSS selectors
await $('#username').setValue('testuser');
await $('.login-button').click();
await $('input[type="password"]').setValue('password');

// Advanced CSS selectors
await $('div.form-group:nth-child(2) input').setValue('value');
await $('button[data-testid="submit"]').click();
await $('ul li:first-child a').click();

XPath Selectors

XPath provides powerful element location capabilities, especially for complex DOM structures.

// Basic XPath
await $('//input[@id="username"]').setValue('testuser');
await $('//button[text()="Login"]').click();

// Advanced XPath
await $('//div[@class="form-group"]//input[@type="text"]').setValue('value');
await $('//table//tr[contains(@class, "active")]//td[2]').getText();

2.2 Element Interactions

Basic Interactions

// Click operations
await $('#button').click();
await $('#link').doubleClick();
await $('#element').rightClick();

// Input operations
await $('#input').setValue('text');
await $('#input').addValue(' more text');
await $('#input').clearValue();

// Form interactions
await $('#checkbox').click();
await $('#dropdown').selectByValue('option1');
await $('#dropdown').selectByText('Option 1');

Advanced Interactions

// Drag and drop
await $('#source').dragAndDrop($('#target'));

// Hover actions
await $('#menu').moveTo();
await $('#submenu').click();

// Key combinations
await $('#input').setValue('text');
await browser.keys(['Control', 'a']);
await browser.keys(['Control', 'c']);

2.3 Waiting Strategies

Explicit Waits

// Wait for element to be displayed
await $('#element').waitForDisplayed({ timeout: 5000 });

// Wait for element to be clickable
await $('#button').waitForClickable({ timeout: 3000 });

// Wait for element to exist
await $('#dynamic-element').waitForExist({ timeout: 10000 });

// Wait for text to appear
await $('#status').waitUntil(async function () {
    return (await this.getText()) === 'Complete';
}, {
    timeout: 5000,
    timeoutMsg: 'Status did not change to Complete'
});
Previous: WebDriverIO Fundamentals Next: Asynchronous Testing with WebDriverIO