I have a form which has a handler attached to the submit event, like this:
$('#myForm').bind('submit', $.proxy(this, 'form_onSubmit'));
I can't work out how to test this line of code to ensure that when the form is submitted, it uses the correct event handler. For example, this doesn't work as the page keeps submitting itself in an infinite loop:
describe('Submitting the form', function() {
it ('Uses the correct event handler', function() {
spyOn(myConstructor, 'form_onSubmit');
$('#myForm').trigger('submit');
expect(myConstructor.form_onSubmit).toHaveBeenCalled();
});
});
I've also been trying to use:
expect($('#myForm')).toHandleWith('submit', myConstructor.form_onSubmit);
But as I haven't been able to find a working example of this anywhere, I'm sure I'm using it incorrectly (Jasmine is throwing the error "Cannot read property 'submit' of undefined" where undefined is this.actual.data("events")).
Can anyone please help? I've been at it for hours! Thanks.
I am using Jasmine jQuery to spy on the event.
https://github.com/velesin/jasmine-jquery#event-spies
Also I am mocking the form using a fixture.
On the form itself (in the fixture) I set the action to "javascript:void(0)" to prevent the form submission from happening.
<form class="js-game-form" action="javascript:void(0)">
</form>
For the test
describe("#submitForm", function(){
it("should submit the form when you press one of the update buttons", function(){
var spyEvent = spyOnEvent(formSelector, 'submit');
$(updateButtonSelector).trigger("click");
expect(spyEvent).toHaveBeenTriggered();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With