Skip to content
This repository has been archived by the owner on Mar 20, 2024. It is now read-only.

Added new function for waiting for an element to appear on page. #344

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/Behat/MinkExtension/Context/MinkContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -21,6 +22,8 @@
*/
class MinkContext extends RawMinkContext implements TranslatableContext
{
const MAXIMUM_WAIT_TIME = 60;

/**
* Opens homepage
* Example: Given I am on "/"
Expand Down Expand Up @@ -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<element>[^"]*)" 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");
}
}