I want to test the Form submission by using jasmine.
The form is defined in a backbone view which looks like this (1).
I implemented the following test (2), but I am not sure how it is effective.
For example if the textarea is empty onError function should be called.
Any ideas the best way to test the submission of a form, in this context, by using 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);
});
});
In your example you are testing your own test.
I rather would propose something like this:
Update
Probably my above code is not gonna work, due like in spying over Router methods the handlers are seted at initializing time so any further
spyis not gonna be called.You should spy at class level and before you have instantiated your View: