Reputation: 4228
In the Backbone
app I am working on, namely the tests for it, I have a view that has it's event hash set to trigger a function when a change
event occurs on a select
element in the DOM
.
When I listen for the call on the spy
I created for that function, this is never called.
How can I manually trigger the change
event for the option
element in the select
element?
I have the following code to create the event:
it('change on element "select" calls "clickedElement"', function () {
// Create a new 'change' event
var event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
// Dispatch it.
this._view.el.querySelector('option[selected]').dispatchEvent(event);
expect(this.clickedElementSpy).has.been.called;
});
Upvotes: 0
Views: 489
Reputation: 3042
One solution possible :
var log = function( val ){ document.body.insertAdjacentHTML('beforeend' ,'<div>' + val + '</div>');
};
var sel = document.getElementsByTagName('select')[0];
sel.onchange = function(){
log('changed')
};
var event = new Event('change');
// Dispatch it.
sel.dispatchEvent(event);
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
So in your use case :
it('change on element "select" calls "clickedElement"', function () {
// Create a new 'change' event
//var event = document.createEvent("HTMLEvents");
//event.initEvent("change", true, true);
var event = new Event('change');
// Dispatch it.
//this._view.el.querySelector('option[selected]').dispatchEvent(event);
this._view.el.querySelector('select').dispatchEvent(event);
expect(this.clickedElementSpy).has.been.called;
});
Upvotes: 1