Java Reference
In-Depth Information
All is well from the beginning of the file UnmanagedFormTester.java until the call to
getText
b
. The call takes a Selenium locator to retrieve the content of the element
named
serverMessage
. The return value is the empty string
C
because the
DOM
model in the object model isn't up to date. Perhaps we need to wait for the server to do
its work and the result to come back. Calling
waitForPageToLoad
doesn't work because
the code doesn't reload the page. Recall that this is an Ajax application; pages don't
reload. Calling
Thread.sleep
after clicking the button doesn't work either. Fortu-
nately, Selenium provides a single powerful
API
for this purpose:
waitForCondition
.
Here it is in action in the class
UnmanagedFormTester
:
@Test
public
void
testFormWithJavaScript()
throws
IOException {
selenium.open(TEST_PAGE);
selenium.click("name=getMessageButton");
selenium.
waitForCondition
(APP_WINDOW +
".document.helloForm.serverMessage.value=='" + EXPECTED_MSG + "'",
"1000");
}
Alternatively, without the refactoring, the JavaScript expression in the first argument
to
waitForCondition
reads:
selenium.browserbot.getCurrentWindow().document.helloForm.serverMessage.
value == 'Hello World'
The
waitForCondition
method waits for a given condition to become true or a time-
out to expire. The method takes two arguments: the first is JavaScript code where the
last expression must evaluate to a Boolean; the second is a timeout
String
expressed
in milliseconds.
Wait for condition API tip
In order for JavaScript to access the application window, you must use the follow-
ing expression:
selenium.browserbot.getCurrentWindow()
For example, to get to the document, use
selenium.browserbot.getCurrentWindow().document
The art of testing Ajax with Selenium is about embedding JavaScript in your
JU
nit
code. This can be confusing because you're embedding JavaScript in Java, but it's
what's required because the Selenium server controlling the web browser will run the
JavaScript for you. In contrast, let's go back to HtmlUnit and see how this test looks in
that framework.