2017-08-31 136 views
1

我想在我的网站上使用硒web驱动程序的JavaScript自动化测试。使用等待与硒web驱动程序异步内容

如何使用wait方法在页面加载时可能未准备好的内容的情况下运行测试,例如数据来自外部api等?

在我的示例中,我的内容正在通过外部js文件加载。你可以在this fiddle中看到页面的样子,因为小提琴被封装在一个iframe中,所以我无法将它链接到我的代码中。

<head> 
    <script src="https://cdn.auth0.com/js/lock/10.2/lock.min.js"></script> 
    </head> 

    <body onload="lock.show();"> 
      <div id="content"> 
      <script type="text/javascript"> 
    var domain = 'contoso.auth0.com'; 
    var clientID = 'DyG9nCwIEofSy66QM3oo5xU6NFs3TmvT'; 

    var lock = new Auth0Lock(clientID, domain); 
    lock.show({ 
    focusInput: false, 
    popup: true, 
    }, function (err, profile, token) { 
    alert(err); 
    }); 
      </script> 
    </div> 
    </body> 

我可以使用睡眠工作,但无法保证在超时完成后我的内容将准备就绪。

const {Builder, By, Key, until} = require('selenium-webdriver'); 

    let driver = new Builder() 
      .forBrowser('firefox') 
      .build(); 

    driver.get('MY_URL') 
    driver.sleep(2000).then(function() { 
     driver.findElement(By.name('email')).sendKeys('[email protected]') 
     driver.findElement(By.name('password')).sendKeys('test') 
     //driver.findElement(By.className('auth0-lock-submit')).click() 
    }) 

但是,如果我尝试用等待

function login() { 
     return driver.findElement(By.name('email')).sendKeys('[email protected]') 
    } 

    driver.get('MY_URL') 
    driver.wait(login, 5000) 

我得到NoSuchElementError: Unable to locate element: *[name="email"]

我怎样才能得到这个工作让我等待我的内容,然后再继续可用。

+0

这是夜间或???你应该为你正在寻找的语言添加一个标签。你有没有相当于'WebDriverWait'?我的背景是C#/ Java,我只是等待显示电子邮件元素等。 – JeffC

+0

[Nightwatch:比\'.pause(1000)\'更好的方法''以避免脆性测试?](https://stackoverflow.com/questions/33224546/nightwatch-better-way-than-pause1000-to-避免脆弱测试) – JeffC

+0

我使用Selenium-Java和Selenium-Python,我不知道Selenium-JavaScript中的语法。但我可以建议你一个策略。你会接受吗? – DebanjanB

回答

1

隐含的等待会告诉网络驱动程序等待一段时间,然后才会抛出“无此类元素异常”。默认设置为0。一旦我们设定的时间,网络驱动程序将等待时间抛出异常之前..

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS); 

尝试使用FluentWait。由要等待并把它传递以下方法

WebElement waitsss(WebDriver driver, By elementIdentifier){ 
Wait<WebDriver> wait = 
new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS) .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); 

return wait.until(new Function<WebDriver, WebElement>() 
{ 
public WebElement apply(WebDriver driver) { 
return driver.findElement(elementIdentifier); 
}}); 
} 

守则明确等待你的元素的函数创建一个:

WebDriverWait wait = new WebDriverWait(driver, 60); 
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[contains(.,'Next')]"))); 

参考: -

https://www.guru99.com/implicit-explicit-waits-selenium.html