GEB TEST WITH SELECT2 JQUERY PLUGIN

  1. Problem

When using Select2 Jquery plugin in my project, there is a problem in writing Geb functional tests because Geb does not understand Select2 via its default select mechanism.

Fortunately, Geb provides the mechanism to extend the default navigators to write our own method in a need of using third party library. Here is the solution.

2. Solution

2.1 Extend navigator classes NonEmptyNavigator and EmptyNavigator

Geb provides two navigators classes NonEmptyNavigator and EmptyNavigator. If the selector $(‘#fieldId’) returns an element, it will be bound to a NonEmptyNavigator, else it will use EmptyNavigator.

Thus, first of all, create two subclasses which extend from NonEmptyNavigator and EmptyNavigator as below:

import geb.Browser
import org.openqa.selenium.WebElement

class NonEmptyNavigator extends geb.navigator.NonEmptyNavigator {

    NonEmptyNavigator(Browser browser, Collection<? extends WebElement> contextElements) {
        super(browser, contextElements)
    }
}
import geb.Browser

class EmptyNavigator extends geb.navigator.EmptyNavigator {
    EmptyNavigator(Browser browser) {
        super(browser)
    }
}

2.2. In GebConfig.groovy, add the below code to use custom navigator

innerNavigatorFactory = { Browser browser, List<WebElement> elements ->
    elements ? new NonEmptyNavigator(browser, elements) : new EmptyNavigator(browser)
}

2.3 Convert the select2 Jquery script to Geb friendly expression by using the built-in javascript executor. 

To do this, add the corresponding method into NonEmptyNavigagor class above

  • Method to set value Select2
void select(String value){ 
     browser.js.exec(firstElement(), value, 'jQuery(arguments[0]).select2("val", arguments[1]);')
  }
  • Method to get the selected value of Select2
String getSelectedValue() {
browser.js.exec(firstElement(), ‘return jQuery(arguments[0]).select2(“val”);’)
}

2.4 Now in your Geb Test, you can call the new methods which have been added to choose the values and get the selected values from Select2

$(‘#fieldId’).select(‘California’)
$(‘#fieldId’).getSelectedValue()

3. References

https://fbflex.wordpress.com/2013/11/25/extending-geb-element/