Categories: AngularJS

Protractor and Dropdowns: validation

Found a good article on how to test AngularJS with Protractor and dropdown menus:

The issue with testing dropdowns in protractor is that you are relying on certain web browser behavior to work. In the article, there is code for how to test dropdowns properly.

Here is a snippet of the code distilled to its essence, the selection of the option elements using Protractor’s locators, clicking an option value and then validating a particular option has been chosen.

let dropdown = element('my-select-dropdown-element'));

// Clicking on the first option of the dropdown
let index = 0;
dropdown.all(by.tagName('option')).then(function(optionElements) {

// Validating that the option has been selected
let expectedOption = 'first_option';
let checkedOptions = element('my-select-dropdown-element'))
  .filter(function(optionElement) {
    // Filter for checked items and that the exact option value was selected
    return optionElement.getAttribute('checked') == true
      && optionElement.getAttribute('value') == expectedOption;
// Expect that the first option was selected

What we’re doing in the above code snippet is we are first selecting the dropdown element. Then we collect all of the option elements of the dropdown and call the click function on the first one.

Afterward, we validate that the correct option was selected by selecting the dropdown element, then searching through the list of options for the checked attribute to be true and the value attribute to have the same value as the expected option.

If you’re interested in Protractor for testing, you may also be interested in using Protractor to take screenshots of what you’re testing with Selenium.

Rudolf Olah is a software development expert with over 8 years of professional software developer experience. He has produced the video courses "Reactive Programming in Python with RxPy, PyQt5 and Tornado" and "Learning AngularJS Testing" for PacktPublishing. Rudolf offers web development training courses for individual developers and for web development teams. He writes about tech leadership, career coaching and project management.