There are two cases to account for:
- Is the element present; meaning does it exist in the DOM.
- Is the element visible; meaning it is in DOM and does not have a hidden or equivalent flag.
For the first case, I use the following helper method:
this.waitForElement = function(locator) {
browser.wait(function() {
return browser.isElementPresent(locator);
}, testData.Timeout.TWO_MINUTES);
};
This will wait for an arbitrary amount of time for the element matching the provided locator to become present (It exists in the DOM).
For the second case, I use this helper method:
this.waitForElementIsVisible = function(el){
let EC = protractor.ExpectedConditions;
browser.wait(EC.visibilityOf(el), testData.Timeout.TWO_MINUTES, "Element did not become visible after 2 minutes");
};
This takes a WebElement
as the single parameter and waits until the element becomes visible (It exists in the DOM and is not hidden via a css style or something)
As a bonus, I also found this helper method to be useful for testing error states in a form:
this.waitForElementIsClickable = function(el){
let EC = protractor.ExpectedConditions;
browser.wait(EC.elementToBeClickable(el), testData.Timeout.TWO_MINUTES, "Element did not become clickable after 2 minutes");
};
Takes a WebElement
as the first parameter and waits until that WebElement can be clicked.
Note, I am using protractor, and reference Protractor in these snippets. So unless you are using Protractor as well, it’s likely these will not work 100% through a straight copy+paste. Should be easy enough to tweak them to suite your setup though.