Home > Mobile >  not able to get the selected option from select options or dropdown in webdriverIO
not able to get the selected option from select options or dropdown in webdriverIO

Time:07-15

To get the selected option from a dropdown or select element, I am using below code block, but the selectedText once out of for loop returns blank, but it should return the value assigned in if condition. can anyone assist?

it('verify select dropdown...', async () => {
        browser.url("https://qavbox.github.io/demo/signup/")
        await browser.pause(2000)
        let select = await $("select[name='sgender']")
        let options = await select.$$('option')
        console.log("options count - "   options.length)

        let selectedText = ""
        options.filter(async option => {
            if (await option.isSelected()) {
              selectedText = await option.getText()
              console.log("inside loop - selectedText is: "   selectedText)
              return
            }
        })
        console.log("outside loop - selectedText is: "   selectedText)
        await browser.pause(2000)
    });

console.log("inside loop - selectedText is: " selectedText)
output - Select:

console.log("outside loop - selectedText is: " selectedText)
Output -

but I am expecting the output of outside loop as "Select:"

CodePudding user response:

The problem seems to be because of how Array.filter or Array.forEach are dealt with asynchronously in nodejs. If you have noticed the console, outside loop is logged before the inside loop.

[0-0] options count - 4
[0-0] outside loop - selectedText is: 
[0-0] inside loop - selectedText is: Select:

This can be fixed by traditional for looping over the array.

it('verify select dropdown...', async () => {
    browser.url('https://qavbox.github.io/demo/signup/');
    await browser.pause(2000);
    let select = await $("select[name='sgender']");
    await select.selectByIndex(1);
    let options = await select.$$('option');
    console.log('options count - '   options.length);

    let selectedText;
    for (let index = 0; index < options.length; index  ) {
      console.log('Before the loop: '   index   ' '   selectedText);
      if (await options[index].isSelected()) {
        selectedText = await options[index].getText();
        console.log('inside loop - selectedText is: '   selectedText);
      }
    }
    console.log('outside loop - selectedText is: '   selectedText);
    await browser.pause(2000);
  });

Outputs:

[0-0] options count - 4
[0-0] Before the loop: 0 undefined
[0-0] Before the loop: 1 undefined
[0-0] inside loop - selectedText is: Male
[0-0] Before the loop: 2 Male
[0-0] Before the loop: 3 Male
[0-0] outside loop - selectedText is: Male
  • Related