0

I'm writing tests using CasperJS for legacy GWT (2.3) code.

I can change the selected value of a ListBox.

document.querySelector('#id_of_select').selectedIndex = 1;

But this does not trigger the onChange() method of a change handler on the ListBox.

I have tried manually dispatching a change event on the select element (jquery is not available on the page):

var evt = document.createEvent("manualchange");
        evt.initEvent("change", false, true);
document.querySelector('#id_of_select').dispatchEvent(evt);

I've also tried it this way.

document.querySelector('#id_of_select').dispatchEvent(new Event('change', { 'bubbles': true }));

Neither approach triggers the onChange method of the change handler. Can anyone suggest a way to get this working?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user1173706
  • 2,612
  • 3
  • 19
  • 29

1 Answers1

1

The jQuery way seems to work in such cases:

casper.fillSelect = function(selectSelector, id){
    this.evaluate(function(sel, id) {
        var select = jQuery(sel);
        select[0].selectedIndex = id;
        select.change();  
    }, selectSelector, id);
};

casper.fillSelect('#id_of_select', 1);

To make that work, you can simply load jQuery into the page by either adding a local copy to options.clientScripts or a remote copy into options.remoteScripts:

var casper = require("casper").create({
    clientScripts: [ "jquery.min.js" ],
    // or
    remoteScripts: [ "http://code.jquery.com/jquery-1.11.3.min.js" ]
});

There is also another way of doing this by pressing the mouse button on the select field and releasing it on a specific option:

casper.mouse.down("#id_of_select");
casper.mouse.up('#id_of_select > option:nth-child(2)'); // the second option
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222