forms | form utilities | map object to form | Search

This code automates the selection of a dropdown menu option on a webpage by finding the dropdown and the desired option based on their labels and values.

Run example

npm run import -- "fill select dropdown"

fill select dropdown

function selectDropdown(client, label, value) {
    return client
        .click('//*[contains(., "' + label + '")][not(*)]/parent::*/*[contains(@role, "listbox")]' +
               '|//*[contains(@aria-label, "' + label + '")]//*[contains(@role, "listbox")]' + 
               '|//*[contains(@aria-label, "' + label + '")]//*[contains(@class, "button-dropdown")]') // [contains(@aria-selected, "true")]
        .pause(1000)
        .click('//*[contains(., "' + label + '")][not(*)]/parent::*[not(self::body)]//*[contains(@role,"option")][contains(.,"' + value + '")]' +
               // handle google angular drop down lists or google calendar drop down
               // TODO: break up this line in to two
               '|//*[contains(@aria-label, "' + label + '")]//*[contains(@class,"menuitem") or contains(@role, "gridcell")][not(contains(@class,"other-month"))][contains(.,"' + value + '")]')
        .pause(1000)
}
module.exports = selectDropdown;

What the code could have been:

function selectDropdown(client, label) {
    const dropdownSelectors = [
        `//*[contains(., '${label}')]/*[contains(@role, 'listbox') or contains(@aria-label, '${label}') or contains(@class, 'button-dropdown')]`,
        `//*[contains(@aria-label, '${label}')][contains(@role, 'listbox') or @role='listbox' or contains(@class, 'button-dropdown')]`,
    ];

    return client
       .click(dropdownSelectors.join(' | '))
       .pause(1000);
}

function selectOption(client, label, value) {
    return client
       .click(`//*[contains(@aria-label, "${label}") and contains(@class, "menuitem") or contains(@role, "gridcell")][not(contains(@class, "other-month")) and contains(.,"${value}")]`)
       .pause(1000);
}

module.exports = { selectDropdown, selectOption };

This code snippet defines a function selectDropdown that automates the process of selecting an option from a dropdown menu on a webpage.

Here's a breakdown:

  1. Function Definition:

  2. Dropdown Selection:

Purpose:

This function provides a way to programmatically select a specific option from a dropdown menu on a webpage, handling various dropdown types and potential variations in their implementation.