Testing Ajax application with Selenium

Ajax, an acronym for Asynchronous JavaScript and XML, is a web development technique for creating interactive and more responsive web applications. The Ajax application works more like a desktop application, meaning that user’s request will not cause an entire page to reload every time, the web browser makes an asynchronous call to the web server to obtain the required data and update only specific parts of the current web page. As result the user gets more interactive, speedy, and usable web pages, but testing AJAX with Selenium will be challenging.

Selenium’s ‘assert’ and ‘verify’ commands might occasionally fail thanks to the asynchronous nature of the Ajax. It may happened that the result doesn’t come back from the server immediately and while ‘assert’ and ‘verify’ commands already trying to verify a new value immediately.

Not experienced testers would recommend to add a ‘pause’ command for a few seconds before the verification. The ‘pause’ suggestion may work in certain cases, because Ajax call may be not completed after pausing for a specific time due to slow machines or network. If the tester set the long pause time it will make the test unacceptably slow and drastically increase testing time.

In this type of tests you should use waitForCondition function in Selenium for Ajax testing. The waitForCondition command evaluates a JavaScript snippet repeatedly, until the snippet returns true. As soon as Selenium detects that the condition returns true, it will stop waiting and Ajax testing will resume.

It is important to note that the selenium in selenium.waitForCondition is a Java object in your test code and the selenium in selenium.browserbot is a javascript object running in the web browser.

Examples:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().loading == false", "20000");

> Condition

> Timeout miliseconds

If you are using AJAX you might find there is an AJAX object on your application. In it will be a activeRequestCount. When the AJAX.activeRequestCount goes to zero, all the AJAX calls are done. So you can wait for an AJAX call to complete with:

selenium.waitForCondition("selenium.browserbot.getCurrentWindow().AJAX.activeRequestCount == 0", "30000");

Thank you πŸ™‚

Β 

Fonts:Β http://www.seleniumguide.com/p/testing-ajax-with-selenium.html

http://darrellgrainger.blogspot.co.uk/2010/03/selenium-rc-java-waitforcondition.html

One thought on “Testing Ajax application with Selenium

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.