-
Notifications
You must be signed in to change notification settings - Fork 852
HowTo Wait
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is sleep()
, which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with WebDriverExpectedCondition is one way this can be accomplished.
// Wait for the page title to be 'My Page'.
// Default wait (= 30 sec)
$driver->wait()->until(
WebDriverExpectedCondition::titleIs('My Page')
);
// Wait for at most 10s and retry every 500ms if it the title is not correct.
$driver->wait(10, 500)->until(
WebDriverExpectedCondition::titleIs('My Page')
);
There are many prepared conditions you can pass to the until()
method. All of them subclass WebDriverExpectedCondition
.
titleIs()
titleContains()
titleMatches()
urlIs()
urlContains()
urlMatches()
presenceOfElementLocated()
presenceOfAllElementsLocatedBy()
elementTextIs()
elementTextContains()
elementTextMatches()
textToBePresentInElementValue()
visibilityOfElementLocated()
$driver->wait(10, 1000)->until(
WebDriverExpectedCondition::visibilityOfElementLocated(WebDriverBy::id('first_name'))
);
-
visibilityOf()
- note the element must already be present in the DOM and you only wait until it became visible
$element = $driver->findElement(WebDriverBy::id('first_name'));
$driver->wait(10, 1000)->until(
WebDriverExpectedCondition::visibilityOf($element)
);
invisibilityOfElementLocated()
invisibilityOfElementWithText()
frameToBeAvailableAndSwitchToIt()
elementToBeClickable()
alertIsPresent()
numberOfWindowsToBe()
stalenessOf()
refreshed()
not()
elementToBeSelected()
elementSelectionStateToBe()
The until()
method accepts also any callable, providing you an possibility to implement custom condition like this:
$driver->wait()->until(
function () use ($driver) {
$elements = $driver->findElements(WebDriverBy::cssSelector('li.foo'));
return count($elements) > 5;
},
'Error locating more than five elements'
);
This example condition will wait until more than 5 elements with selector li.foo
appears.
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
$driver->manage()->timeouts()->implicitlyWait(10);
It is recommended to use explicit wait instead of the implicit one. See for example this Stackoverflow answer for some reasoning.