Reputation: 1
I've just start looking at implementing tests with Selenium using a Mocha/Chai framework & am struggling with a login function. I want to check an item is present/displayed & to click it if it is.
Currently my test waits on the page loading & I want something like the following, which currently doesn't work:
var elementOnPage = driver.findElement(By.('elementId')).isDisplayed();
//var elementOnPage = driver.findElement(By.('elementId')).exist;
if(elementOnPage == true){
driver.findElement(By.('elementId')).click();
}
else{
driver.findElement(By.('anotherElement')).click();
}
I've also tried the commented out line above but neither seems to work. The code always seems to hit the 2nd part of the if statement before continuing. If the element I'm checking for is present then the test executes the next line but if it's not present then the test fails with a "NoSuchElementError: No such element".
I also didn't realise I could use stuff like exists(), isPresent() or isElementPresent() either.
Does anyone have any ideas or point me in the right direction? I'm quite new to this.
Cheers
Upvotes: 0
Views: 3975
Reputation: 151461
The return value of isDisplayed
is a promise, but you treat it as a boolean.
You need to do something like:
driver.findElement(By.id('elementId')).isDisplayed().then(function (displayed) {
if (displayed) {
driver.findElement(By.id('elementId')).click();
}
else{
driver.findElement(By.id('anotherElement')).click();
}
});
Or more concisely:
driver.findElement(By.id('elementId')).isDisplayed().then(function (displayed) {
driver.findElement(By.id(displayed ? 'elementId' : 'anotherElement')).click();
});
By the way By.('elementId')
cannot work. I've assumed you meant By.id('elementId')
.
Upvotes: 1