Sunday, December 13, 2009

Design of Selenium tests for ASP.NET: Testing AJAX

When it comes to AJAX, UI tests started to behave unexpectedly. Sometimes they fail, sometimes pass:

AJAX request on server

Selenium tests failed when page has AJAX requests.

The main trick in testing AJAX is to wait until asynchronous request is completed. There is an universal waitForCondition function which gets JavaScript Boolean expression as argument, and waits until this expression returns true.

public HomePageFlow AssertUserName(string userName)
{
Navigator.WaitForText(_home.UserName.Selector);

Assert.That(_home.UserName.GetText(), Is.EqualTo(userName));

return this;
}
public void WaitForText(string selector)
{
selector = selector.Replace(@"'", @"\'");

string script = string.Format("var value = selenium.getText('{0}'); value.length > 0;", selector);

_selenium.WaitForCondition(script, Timeout);
}

It was needed to change only Flows to tell them about AJAX behavior. It is not needed to change any tests, and this is reasonable – because actually nothing was changed from user and UI tests prospective in UI. This means that correct level of abstraction was selected.

using NUnit.Framework;
using Tests.SmokeTest.Core;

namespace Tests.SmokeTest.Tests
{
[TestFixture]
public class HomeTest : TestBase
{
[Test]
public void CheckCurrentUserName()
{
Start
.LoginAndGoToHomePage()
.AssertUserName("admin");
}
}
}
All sources are available in design-of-selenium-tests-for-asp-net sample solution.

kick it on DotNetKicks.com

0 comments: