Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a form submission handler with Jasmine jQuery

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.

like image 610
user399050 Avatar asked Nov 01 '12 17:11

user399050


1 Answers

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();
    });
});
like image 175
Tony Avatar answered Sep 21 '22 05:09

Tony