Skip to content

Instantly share code, notes, and snippets.

@fadonascimento
Created October 30, 2017 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fadonascimento/6e489b1a4c923bad89c4b6f96712aa78 to your computer and use it in GitHub Desktop.
Save fadonascimento/6e489b1a4c923bad89c4b6f96712aa78 to your computer and use it in GitHub Desktop.
behat selenium wait for steps
class FeatureContext extends MinkContext {
/**
* @Given /^I wait for css element "([^"]+)" to (appear|disappear)$/
*/
public function iWaitForCssElement($element, $appear)
{
$xpath = $this->getSession()->getSelectorsHandler()->selectorToXpath('css', $element);
$this->waitForXpath($xpath, $appear == 'appear');
}
private function waitForXpath($xpath, $appear)
{
$this->waitFor(function($context) use ($xpath, $appear) {
$visible = $context->getSession()->getDriver()->isVisible($xpath);
return $appear ? $visible : !$visible;
});
}
private function waitForXpathNode($xpath, $appear)
{
$this->waitFor(function($context) use ($xpath, $appear) {
try {
$nodes = $context->getSession()->getDriver()->find($xpath);
if (count($nodes) > 0) {
assertEquals(1, count($nodes), "more than one element matched '$xpath'");
$visible = $nodes[0]->isVisible();
return $appear ? $visible : !$visible;
} else {
return !$appear;
}
} catch (WebDriver\Exception $e) {
if ($e->getCode() == WebDriver\Exception::NO_SUCH_ELEMENT) {
return !$appear;
}
throw $e;
}
});
}
/**
* @Given /^I wait for text "([^"]+)" to (appear|disappear)$/
*/
public function iWaitForText($text, $appear)
{
$this->waitForXpathNode(".//*[contains(normalize-space(string(text())), \"$text\")]", $appear == 'appear');
}
private function waitFor($fn, $timeout = 5000)
{
$start = microtime(true);
$end = $start + $timeout / 1000.0;
while (microtime(true) < $end) {
if ($fn($this)) {
return;
}
}
throw new \Exception("waitFor timed out");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment