Created
February 27, 2015 18:48
-
-
Save jbouzekri/7f061771bf8d20b4f0d3 to your computer and use it in GitHub Desktop.
A nice wait for js calls ending function in behat
This file contains 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
<?php | |
/** | |
* @author Gildas Quéméner <gildas@akeneo.com> | |
* @copyright 2013 Akeneo SAS (http://www.akeneo.com) | |
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) | |
*/ | |
use Behat\Behat\Exception\BehaviorException; | |
use Behat\Mink\Driver\Selenium2Driver; | |
/** | |
* Wait | |
* | |
* @param integer $time | |
* @param string $condition | |
* | |
* @throws BehaviorException If timeout is reached | |
*/ | |
public function wait($time = 10000, $condition = null) | |
{ | |
if (!$this->getSession()->getDriver() instanceof Selenium2Driver) { | |
return; | |
} | |
$start = microtime(true); | |
$end = $start + $time / 1000.0; | |
if ($condition === null) { | |
$defaultCondition = true; | |
$conditions = [ | |
"document.readyState == 'complete'", // Page is ready | |
"typeof $ != 'undefined'", // jQuery is loaded | |
"!$.active", // No ajax request is active | |
"$('#page').css('display') == 'block'", // Page is displayed (no progress bar) | |
"$('.loading-mask').css('display') == 'none'", // Page is not loading (no black mask loading page) | |
"$('.jstree-loading').length == 0", // Jstree has finished loading | |
]; | |
$condition = implode(' && ', $conditions); | |
} else { | |
$defaultCondition = false; | |
} | |
// Make sure the AJAX calls are fired up before checking the condition | |
$this->getSession()->wait(100, false); | |
$this->getSession()->wait($time, $condition); | |
// Check if we reached the timeout unless the condition is false to explicitly wait the specified time | |
if ($condition !== false && microtime(true) > $end) { | |
if ($defaultCondition) { | |
foreach ($conditions as $condition) { | |
$result = $this->getSession()->evaluateScript($condition); | |
if (!$result) { | |
throw new BehaviorException( | |
sprintf( | |
'Timeout of %d reached when checking on "%s"', | |
$time, | |
$condition | |
) | |
); | |
} | |
} | |
} else { | |
throw new BehaviorException(sprintf('Timeout of %d reached when checking on %s', $time, $condition)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A really good function, thanks!
I have searched for the whole last days and nothing...
And your code is so easy to comprehend and modify 👍