简体   繁体   中英

Selenium Wait for AJAX response

I have a page which has a "status" field, which has a value "In Progress". Now on some action (button click), the status changes to Completed. I need to check for the same using Selenium.

getVisibleElement(By.id("status")).getText()

Now the issue is the status does not change immediately from In Progress to Completed, once the button is clicked. It happens after an AJAX response is received in some seconds. And when my code tries to assert the status text, it actually gets the stale value In Progress and hence it fails the test.

Again please remember even though getVisibleElement() has timeout defined, it does not help me here since the element is anyways present. It is just rendered again on AJAX request (post button click).

How do I fix the same? Can adding a fixed delay work, just before the assert. If yes, how do I do that in selenium?

If your use case is as follows

  1. User will come the page
  2. In Progress is displayed
  3. User press the button
  4. After some time text changes to Completed

Then you can use Web Drivers Explicit Waits like this

@Test
public testProgress() {
    driver.get("progressPage.html");
    assertEquals("In Progress", driver.findElement(By.id("progressBar").getText());
    WebElement myDynamicElement = (new WebDriverWait(driver, 10))
       .until(ExpectedConditions.textToBePresentInElement(By.id("progressBar")));
    assertEquals("Completed", driver.findElement(By.id("progressBar").getText());
}

Use the executeAsync to inject a javascript piece which will listen to a change of that value and return when the desired value is reached or timeout kicks in.

Take a look at the answer on https://stackoverflow.com/a/28057738/475949

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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