One of the biggest struggles while testing web applications that use AJAX is dealing with the timing issues caused by asynchronous nature of the request. A common solution is using timeouts to wait for the AJAX call to be completed. This could cause lots of timing issues. Using Geb there is a better way to determine that the AJAX call and its callback has been completed.

In this blog post we will test the W3Schools website which has a button on it which executes an AJAX request: http://www.w3schools.com/ajax/ajax_example.asp

First we change our baseUrl in the GebConfig.groovy file to the w3school site:

baseUrl = "http://www.w3schools.com/"

Second we define the W3schools page with the needed content and the makeRequest method which clicks the button.

import geb.Page

class WwwSchoolsAjaxExamplePage extends Page{

  private  static final DEFAULT_DIV_CONTENT = 'Let AJAX change this text'

  static url = "ajax/ajax_example.asp"

  static at = {
      title=="AJAX Example"
  }

  static content = {
      theButton { $(".example button") }
      theResultDiv { $("#myDiv") }
  }

  def makeRequest() {
      theButton.click()
      waitFor { theResultDiv.text()!=DEFAULT_DIV_CONTENT }
  }

}

The key statement here is the waitFor line. This will wait till the condition in the closure returns true. The waitFor uses the default timeout configuration which is for Geb 5 seconds.

Next we're going to make our test which verifies our content has been updated.

import geb.spock.GebReportingSpec

class AjaxRequestSpec extends GebReportingSpec{

  def "Validate if content gets updated after button click"() {

          given:
          to WwwSchoolsAjaxExamplePage

          when:
          makeRequest()

          then:
           theResultDiv.children()[0].text() == "AJAX is not a new programming language."
           theResultDiv.children()[1].text() == "AJAX is a technique for creating fast and dynamic web pages."

  }

}

When you run the now run the test, the test will succesfully verify the updated content of the w3schools website.

Done with Groovy 2.4.3

shadow-left