Here is the code about the javascript submit request (1).
Here is the test about mocking the ajax request by using jasmine (2).
I would like to mock the server b
It would be much easier to test if you had a var with the ajax request promise object. In that case you could do:
it('should do an async thing', function() {
var mutex = 1;
var promF = jasmine.createSpy('prF');
runs( function() {
var promise1 = $.ajax();
promise1.always(function(){
mutex--;
});
promise1.fail(function(){
promF();
});
});
waitsFor(function(){
return !mutex;
}, 'Fetch should end', 10000);
runs( function() {
expect(promF).toHaveBeenCalled();
});
});
Below I post untested code that might suit you. I suppose that the ajax call is initialized from the .submit() class? Maybe you should initialize the ajax request from a runs() block and not from beforeEach(), but you should try which one works.
describe('When Submit button handler fired and city is defined', function () {
var ajaxRequestSpy,
failSpy, successSpy, alwaysSpy,
mutex;
beforeEach(function () {
ajaxRequestSpy = spyOn(backendController, 'ajaxRequest').andCallThrough();
failSpy = spyOn(ajaxRequestSpy(), 'fail').andCallThrough()
successSpy = spyOn(ajaxRequestSpy(), 'success').andCallThrough();
mutex = 1; // num of expected ajax queries
alwaysSpy = spyOn(ajaxRequestSpy(), 'always').andCallFake(function() {
mutex--;
});
this.view = new MyView({
el: $('')
});
this.view.$el.find('form').submit();
});
it('backendController.ajaxRequest should be called', function () {
runs( function() {
// maybe init ajax here ?
});
waitsFor( function() {
return !mutex;
}, 'ajax request should happen', 5000);
runs( function() {
expect(ajaxRequestSpy).toHaveBeenCalled(); // true
expect(failSpy).toHaveBeenCalled(); // Error: Expected spy fail
// to have been called.
});
});
});
But, I am not sure that the line
failSpy = spyOn(ajaxRequestSpy(), 'fail').andCallThrough();
does what you want. Is it possible to spy on another spy? And if yes why are you calling the spy ? Maybe you should try
failSpy = spyOn(ajaxRequestSpy, 'fail').andCallThrough();