我想使用jasmine测试表单提交 表格在骨干视图中定义,如下所示(1) 我实施了以下测试(2),但我不确定它是如何有效的 例如,如果textarea为空,则应调用Error函数 在这种情况下,使用jasmine来测试表单提交的最佳方法是什么想法?
(1)
var MyView = Backbone.View.extend({
events: {
'focus [data-tid="message"]' : 'focusForm',
'blur [data-tid="message"]' : 'blurForm',
'submit form' : 'submitForm'
},
focusedClass: 'is-form-focused',
focusForm: function () {
this.$el.find('form').addClass(this.focusedClass);
},
blurForm: function () {
this.$el.find('form').removeClass(this.focusedClass);
},
submitForm: function (event) {
event.preventDefault();
var formElement = event.currentTarget,
message = this.$el.find('.message');
if (formElement.checkValidity && !formElement.checkValidity()) {
this.onError();
} else {
// makes a POST ajax call
backendController.submitFeedback(message.val()).done(this.onSuccess).fail(this.onError);
}
},
onError: function () {
this.$el.find('.message').focus();
},
onSuccess: function () {
this.$el.find('.message').val('');
this.$el.find('form').removeClass(this.focusedClass);
}
});
(2)
describe('When Submit button handler fired', function () {
beforeEach(function () {
this.popupSpy = sinon.spy();
this.view.render();
this.view.$el.find('form').on('submit', this.popupSpy);
this.view.$el.find('form').trigger('submit');
});
it('submitForm should be called', function () {
expect(this.popupSpy.callCount).toBe(1);
});
});
答案 0 :(得分:4)
在您的示例中,您正在测试自己的测试。
我宁愿提出这样的事情:
// code simplified and no tested
describe("When Submit button handler fired", function () {
it("submitForm should be called", function () {
this.view.render();
spyOn( this.view, "submitForm" );
this.view.$el.find("form").submit();
expect( this.view.submitForm ).toHaveBeenCalled();
});
});
可能我上面的代码不起作用,因为在spying over Router methods中处理程序在初始化时被设置,因此任何进一步的spy
都不会被调用。
您应该在课程级别和实例化视图之前进行间谍活动:
// code simplified and no tested
describe("When Submit button handler fired", function () {
it("submitForm should be called", function () {
spyOn( MyView.prototype, "submitForm" );
this.view = new MyView();
this.view.render();
this.view.$el.find("form").submit();
expect( MyView.prototype.submitForm ).toHaveBeenCalled();
});
});