From f32974aa19442c95e417324d513b54421983ea02 Mon Sep 17 00:00:00 2001 From: Tim Jabs Date: Fri, 5 Jul 2019 16:53:26 +0200 Subject: [PATCH] Added new function for waiting for an element. --- .../MinkExtension/Context/MinkContext.php | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/Behat/MinkExtension/Context/MinkContext.php b/src/Behat/MinkExtension/Context/MinkContext.php index b1f500a4..266b4f80 100644 --- a/src/Behat/MinkExtension/Context/MinkContext.php +++ b/src/Behat/MinkExtension/Context/MinkContext.php @@ -12,6 +12,7 @@ use Behat\Behat\Context\TranslatableContext; use Behat\Gherkin\Node\TableNode; +use Behat\Mink\Exception\ElementNotFoundException; /** * Mink context for Behat BDD tool. @@ -21,6 +22,8 @@ */ class MinkContext extends RawMinkContext implements TranslatableContext { + const MAXIMUM_WAIT_TIME = 60; + /** * Opens homepage * Example: Given I am on "/" @@ -570,4 +573,44 @@ protected function fixStepArgument($argument) { return str_replace('\\"', '"', $argument); } + + /** + * Waits for an element to appear on page. + * Example: Then I wait for element "#someID" to appear + * + * @Then I wait for element "(?P[^"]*)" to appear + */ + public function iWaitForElementToAppear($element, $secondsToWait = null) + { + $waitFunction = function ($context) use ($element) { + try { + $context->assertElementOnPage($element); + } catch (ElementNotFoundException $e) { + return false; + } + + return true; + }; + + $this->spin($waitFunction, $secondsToWait); + } + + /** + * Executes a function and waits until the function returns true. + * @see http://docs.behat.org/en/v2.5/cookbook/using_spin_functions.html#adding-a-timeout + */ + private function spin($callback, $maxTimeToWait = null) + { + $waitingTime = $maxTimeToWait === null ? self::MAXIMUM_WAIT_TIME : $maxTimeToWait; + $stopTime = time() + $waitingTime; + while (time() < $stopTime) { + if ($callback($this)) { + return; + } + + usleep(250000); + } + + throw new \RuntimeException("Spin function timed out after {$waitingTime} seconds"); + } }