Skip to content Skip to sidebar Skip to footer

How Do I Test A Function That Calls An Ajax Function Without Firing It Using Jasmine?

I've checked in How do I verify jQuery AJAX events with Jasmine? and How to test an Angular controller with a function that makes an AJAX call without mocking the AJAX call? but fo

Solution 1:

I suggest mocking out the call rather than actually calling it. The granularity is up to you, you can either stub the ajax call, or stub the whole submit function.

Here is how you can stub the submit function:

spyOn(controller, 'submit').and.callFake(function() {
    DataService.ticketNumber = somevalue;
});

Place that code prior to the actually call to the controller which caller.clickSubmit().

You can then follow up with expectations on the spy, such as:

expect(controller.submit).toHaveBeenCalled()

Or any of the other expectations related to spyOn.

Here are the jasmine docs: http://jasmine.github.io/2.0/introduction.html Look down in the 'spies' area.

If you want to mock up the ajax call, you will have to mock a promise like this:

spyOn($, 'ajax').and.callFake(function() {
    var deferred = $q.defer();
    deferred.resolve(someResponse);
    return deferred.promise;
});

Also, in order to get the code waiting on the promise to resolve, after the submit call has been made, you need to run a $scope.$digest() so that angular can handle the promise resolution. Then you can check your expectations on code that depended on the resolution or rejection of the promise.

Post a Comment for "How Do I Test A Function That Calls An Ajax Function Without Firing It Using Jasmine?"