Webdriver.IO - check in a non-blocking way whether

2020-03-30 06:34发布

问题:

Rookie question. I am using webdriver.io to write Appium end to end tests.

I am using these commands to check the presence of an element:

  • $(selector)
  • browser.waitForVisible(selector, timeout, waitForAppearOrDisappear);
  • browser.element('selector')

They all block my tests if the element is not found.

How can I check whether an element exists in a particular moment without blocking the test execution?

I cannot find anything in the (concise) documentation.

PS. This should do the trick browser.findElement(By.css('[data-qa="some-id"]')); but it's not a wdio command. (findElement and By are not recognized)


npm dependencies:

"appium": "^1.10.0",
"appium-doctor": "^1.6.0",
"wdio-appium-service": "^0.2.3",
"wdio-jasmine-framework": "^0.3.8",
"wdio-spec-reporter": "^0.1.5",
"webdriverio": "^4.14.1",

回答1:

Use findElements instead - https://webdriver.io/docs/api/element/$$.html:

$$(selector)

This should return you an empty array if the element can't be found, it should not cause a failure though.



回答2:

Well, the simples way would be to abuse the fact that querying the Selenium server (using $ / element) is a non-breaking operation.

Suppose you have to query 2 elements, one has rendered inside the DOM, the other didn't (or the element doesn't exist altogether).

let thisLoaded = $('span.coreSpriteFacebookIconInverted');
let thisDidnt = $('span.coreSpriteInstagramIconInverted');

The two variables would have the following contents:

thisDidnt = { 
  sessionId: '7056961e1950b5c54827a51c137cca96',
  value: { ELEMENT: '0.8611270215748772-1',
           'element-6066-11e4-a52e-4f735466cecf': '0.8611270215748772-1' },
  selector: 'span.coreSpriteFacebookIconInverted',
  _status: 0 
}

thisDidnt = { 
  type: 'NoSuchElement',
  message: 'An element could not be located on the page using the given search parameters.',
  state: 'failure',
  sessionId: '7056961e1950b5c54827a51c137cca96',
  value: null,
  selector: 'span.coreSpriteInstagramIconInverted' 
}

Thus, you can now proceed to do your checks ...

if (thisLoaded.value) {
  // > if element loaded <
} else { 
  // > if element didn't load <
}

I'll add more when I get home ...