简体   繁体   English

Mocha / Chai-仅当元素存在,显示或存在时,才单击它进行测试

[英]Mocha/Chai - Test to click an element only if it's present, displayed or exists

I've just start looking at implementing tests with Selenium using a Mocha/Chai framework & am struggling with a login function. 我刚刚开始考虑使用Mocha / Chai框架使用Selenium进行测试,并且正在尝试使用登录功能。 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语句的第二部分。 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". 如果存在我要检查的元素,则测试将执行下一行,但如果不存在,则测试将失败,并显示“ NoSuchElementError:No such element”。

I also didn't realise I could use stuff like exists(), isPresent() or isElementPresent() either. 我也没有意识到我可以使用诸如exist(),isPresent()或isElementPresent()之类的东西。

Does anyone have any ideas or point me in the right direction? 有没有人有任何想法或向我指出正确的方向? I'm quite new to this. 我对此很陌生。

Cheers 干杯

The return value of isDisplayed is a promise, but you treat it as a boolean. isDisplayed的返回值是一个承诺,但是您将其视为布尔值。

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. 顺便说一句By.('elementId')无法正常工作。 I've assumed you meant By.id('elementId') . 我假设您是说By.id('elementId')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM