Skip to content

Instantly share code, notes, and snippets.

@netraagal
Last active March 16, 2018 15:48
Show Gist options
  • Save netraagal/be6034613abb89a5765e0cd218db35a9 to your computer and use it in GitHub Desktop.
Save netraagal/be6034613abb89a5765e0cd218db35a9 to your computer and use it in GitHub Desktop.
Behat, MinkExtension & Selenium2 Driver - functions to wait
<?php
/**
* some functions to make a pause (minutes, seconds or milliseconds)
* The last one is a little more tricky as she will stop the Scenario to wait for the end of the loading of the
* scripts behind (you must be cautious if a script is created to run all the time)
*
* @author netraagal
*/
namespace App\Features;
use Behat\Mink\Driver\Selenium2Driver;
use \Exception;
class TimerFeatureContext extends MinkContext implements SnippetAcceptingContext
{
/**
* waitMinutes
*
* @When /^(?:|I )wait (?:|for )(?P<time>\d+) minutes?$/
*
* @param int $time number of minutes to wait
* @return FeatureContext
*/
public function waitMinutes(int $time): self
{
sleep(60 * $time);
return $this;
}
/**
* waitSeconds
*
* @When /^(?:|I )wait (?:|for )(?P<time>\d+) seconds?$/
*
* @param int $time number of seconds to wait
* @return FeatureContext
*/
public function waitSeconds(int $time): self
{
sleep($time);
return $this;
}
/**
* waitMilliseconds
*
* @When /^(?:|I )wait (?:|for )(?P<time>\d+) milliseconds?$/
*
* @param int $time number of milliseconds to wait
* @return FeatureContext
*/
public function waitMilliseconds(int $time): self
{
sleep($time / 1000);
return $this;
}
/**
* waitLoading
* Not the author but the function is to much based on what he has done to not be named
* @author Gildas Quéméner <gildas@akeneo.com>
*
* @When /^(?:|I )wait (?:|for )(?:|end of )loading$/
*
* @return FeatureContext
*/
public function waitLoading(): self
{
$session = $this->getSession();
if (!$session->getDriver() instanceof Selenium2Driver)
return $this;
$time = 15000;
$conditions = [
"document.readyState == 'complete'",
"typeof $ != 'undefined'",
"!$.active",
];
$condition = implode(' && ', $conditions);
$this->waitMilliseconds(100);
$session->wait($time, $condition);
if (!$session->evaluateScript($condition)) {
throw new Exception(sprintf(
'Timeout of %d reached when checking on "%s"',
$time,
$condition
));
}
foreach ($conditions as $condition) {
$result = $this->getSession()->evaluateScript($condition);
if (!$result) {
throw new Exception(sprintf(
'Timeout of %d reached when checking on "%s"',
$time,
$condition
));
}
}
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment