使用Jasmine jQuery测试表单提交处理程序

use*_*050 5 forms jquery jasmine

我有一个表单,其中有一个附加到提交事件的处理程序,如下所示:

$('#myForm').bind('submit', $.proxy(this, 'form_onSubmit'));
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何测试这行代码以确保在提交表单时,它使用正确的事件处理程序.例如,这不起作用,因为页面一直在无限循环中提交自己:

describe('Submitting the form', function() {
    it ('Uses the correct event handler', function() {
        spyOn(myConstructor, 'form_onSubmit');
        $('#myForm').trigger('submit');
        expect(myConstructor.form_onSubmit).toHaveBeenCalled();
    });
});
Run Code Online (Sandbox Code Playgroud)

我也一直试图使用:

expect($('#myForm')).toHandleWith('submit', myConstructor.form_onSubmit);
Run Code Online (Sandbox Code Playgroud)

但是由于我无法在任何地方找到这样的工作示例,我确定我使用它不正确(Jasmine抛出错误"无法读取属性'提交'未定义"其中undefined是this.actual.数据( "事件")).

有人可以帮忙吗?我已经好几个小时了!谢谢.

Ton*_*ony 8

我正在使用Jasmine jQuery来监视这个事件.

https://github.com/velesin/jasmine-jquery#event-spies

我也在使用夹具嘲笑表格.

在表单本身(在fixture中)我将操作设置为"javascript:void(0)"以防止表单提交发生.

<form class="js-game-form" action="javascript:void(0)">
</form>
Run Code Online (Sandbox Code Playgroud)

为了测试

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();
    });
});
Run Code Online (Sandbox Code Playgroud)