...let John help you code



How to handle AJAX call using Selenium Webdriver

Asked by:
Derek
May 11, 2017, 14:15

2 Answers

Answer :
Code

Preview
 

15

To handle AJAX call, different wait methods should be applied
  • ThreadSleep

  • Implicit Wait

  • Explicit Wait

  • WebdriverWait

  • Fluent Wait

  • 	
    public void test_HandleAjaxCall() {
    By container = By.cssSelector(".container");
    wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.presenceOfElementLocated(container));
    //Get the text before performing an ajax call
    WebElement noTextElement = driver.findElement(By.className("radiobutton"));
    String textBefore = noTextElement.getText().trim();
    //Click on the radio button
    driver.findElement(By.id("yes")).click();
    //Click on Check Button
    driver.findElement(By.id("buttoncheck")).click();
    /*Get the text after ajax call*/
    WebElement TextElement = driver.findElement(By.className("radiobutton"));
    wait.until(ExpectedConditions.visibilityOf(TextElement));
    String textAfter = TextElement.getText().trim();

    /*Verify both texts before ajax call and after ajax call text.*/
    Assert.assertNotEquals(textBefore, textAfter);
    System.out.println("Ajax Call Performed");

    String expectedText = "Radio button is checked and it's value is Yes";

    /*Verify expected text with text updated after ajax call*/
    Assert.assertEquals(textAfter, expectedText);
    driver.close();
    }
    }
    Addy


    3

    The biggest challenge in handling Ajax call is knowing the loading time for the web page. Since the loading of the web page will last only for a fraction of seconds, it is difficult for the tester to test such application through automation tool. For that, Selenium Webdriver has to use the wait method on this Ajax Call.

    So by executing this wait command, selenium will suspend the execution of current test case and wait for the expected or new value. When the new value or field appears, the suspended test cases will get executed by Selenium Webdriver.
    selPat