March 26, 2011

Working with AJAX pages or elements

AJAX stands for Asynchronous JavaScript and XML

 AJAX allows the Web page to retrieve small amounts of data from the server without reloading the entire page. In AJAX driven web applications, data is retrieved from server without refreshing the page.

Using andWait commands will not work as the page is not actually refreshed. Pausing the test execution for a certain period of time is also not a good approach as web element might appear later or earlier than the stipulated period depending on the system’s responsiveness, load or other uncontrolled factors of the moment, leading to test failures. The best approach would be to wait for the needed element in a dynamic period and then continue the execution as soon as the element is found.


This is done using waitFor commands, as waitForElementPresent , which wait dynamically, checking for the desired condition every second and continuing to the next command in the script as soon as the condition is met.


Below is one example how to handle AJAX applications....


package newone;



import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;


public class Ajax extends SeleneseTestCase{

public Selenium selenium;
public SeleniumServer seleniumserver;

@Before
public void setUp() throws Exception {

seleniumserver = new SeleniumServer();
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://");
seleniumserver.start();
selenium.start();

}

@Test
public void testAjax() throws Exception
{
selenium.open("http://ajaximpact.com/");
selenium.windowMaximize();
assertEquals("AJAX Tutorials, Examples, News, Events and much more", selenium.getTitle());
//Click on Products Link
selenium.click("Image12");
verifyEquals("AJAX PRODUCTS", selenium.getTitle());
//Waiting for Element until 60 seconds--we can change it to any value
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("link=FarPoint Spread for Web Forms")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

//After the link or element is present it will come out of for loop and execute the next command
selenium.click("link=FarPoint Spread for Web Forms");
selenium.waitForPageToLoad("30000");
assertEquals("Ajax Impact : FarPoint Spread for Web Forms", selenium.getTitle());
Thread.sleep(1000);
}
@After
public void tearDown() throws InterruptedException{
selenium.stop();
seleniumserver.stop();
}

}


Hope this post will help you....while working with AJAX applications..........


No comments:

Post a Comment