Reputation: 13400
In order to check the submission of an ajax request, when a user submit a form, I implemented the following test using jasmine (1).
The test is successfully passed but looking at javascript console I get the following error 500 (Internal Server Error)
.
Since I don't care the server response, my questions are:
1) Should I or should I not care about this error.
2) Will it be better to fake the ajax request to avoid Internal Server Error
? if yes, how in my context?
(1)
define([
'backendController'
], function (backendController) {
// some code
describe('When button handler fired', function () {
beforeEach(function () {
spyOn(backendController, 'submitRequest1').andCallThrough();
this.view = new MyView({
el: $('<div><form><input type="submit" value="Submit" /></form></div>')
});
this.view.$el.find('form').submit();
});
it('backendController.submitRequest1 should be called', function () {
expect(backendController.submitRequest1).toHaveBeenCalled();
});
});
});
(2)
// backendController object
return {
submitRequest1: function (message) {
return $.ajax({
url: 'someUrl',
type: 'POST',
dataType: 'json',
data: {
message: message
}
}).done(function () {
// some code
});
}
}
(3)
// submitForm in MyView
submitForm: function (event) {
event.preventDefault();
var formElement = event.currentTarget;
if (formElement.checkValidity && !formElement.checkValidity()) {
this.onError();
} else {
backendController. submitRequest1('some data').done(this.onSuccess).fail(this.onError);
}
}
Upvotes: 2
Views: 3011
Reputation: 38772
Your test says "backendController.submitRequest1 should be called" so you only care about the method to be called. So, just don't andCallThrough()
and you'll be free of troubles.
Maybe you have to preventDefault()
in the submit event so:
spyOn(backendController, 'submitRequest1').andCallFake(function(e) { e.preventDefault(); });
After checking the rest of your code you have added to the question I still suggest to stop your code execution as sooner as possible. Just until the test in arriving, and this is still until backendController.submitRequest1()
is called.
In this case is not enough with a simple mock in the method due the return of this method is used subsequently and your mock should respect this:
// code no tested
var fakeFunction = function(){
this.done = function(){ return this };
this.fail = function(){ return this };
return this;
}
spyOn(backendController, 'submitRequest1').andCallFake( fakeFunction );
When things start to be so complicate to test is a symptom that maybe they can be organized better.
Upvotes: 1