Created
November 6, 2018 06:15
-
-
Save kilip/62bfb11f0dd05b91f0a2c8caaee923c0 to your computer and use it in GitHub Desktop.
behat selenium wait for steps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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