I just started using Protractor to write tests. I am wondering what the difference is between the isPresent()
and isDisplayed()
methods.
The API definitions
So... in what cases are they different?
I just started using Protractor to write tests. I am wondering what the difference is between the isPresent()
and isDisplayed()
methods.
The API definitions
So... in what cases are they different?
isPresent is true if element exists in a page (in DOM), but can be hidden (display: none in css) isDisplayed is true only if isPresent is true and element is visible
isDisplayed
resolves to whether the element is visible or not, but throws an exception if it is not in the DOM.
isPresent
resolves to whether it is there in the DOM or not, regardless of whether it is actually visible or not. It doesn't throw an exception.
The following code can be used to avoid the exception that isDisplayed throws if the element is not found in the DOM :
function isVisible(e) {
var deferred = protractor.promise.defer();
if (e) {
e.isDisplayed().then(
// isDisplayed Promise resolved
function(isDisplayed) {
deferred.fulfill(isDisplayed);
},
// Silencing the error thrown by isDisplayed.
function(error) {
deferred.fulfill(false);
}
);
}
else {
deferred.reject(new Error('No element passed'));
}
return deferred.promise;
}
Even an object with both the visibility and presence can be passed while resolving, for example :
deferred.fulfill({
visible: isDisplayed,
present: true
});
However, this won't work well with expect statements.
IsPresent(): Returns TRUE if element exists in DOM(may or may not be hidden) else returns false
IsDisplayed():
If you get an error when calling isDisplayed()
because the element is not on the page, i.e you get NoSuchElementError: No element found using locator
, then do this:
Simply wrap .isDisplayed()
in your own method and handle the unresolved/rejected promise
like below:
function isTrulyDisplayed (elementToCheckVisibilityOf) {
return elementToCheckVisibilityOf.isDisplayed().then(function (isDisplayedd) {
return isDisplayedd;
}).then(null, function (error) {
console.log('A NoSuchElement exception was throw because the element is NOT displayed so we return false');
return false;
}); };
Hope this helps someone out there !
There is a major difference between isDisplayed() and isPresent().
isDisplayed() - Your element is present on the page but it is displayed.
isPresent() - Your element is present in entire DOM of the page. Probably it can be hidden or not disabled, but present.
You should not use isPresent() when you need to validate on specific element you are searching, rather you can use it to validate some other checks based on that element's presence.