How do I test a function that calls an AJAX function without firing it using jasmine?

安稳与你 提交于 2019-12-01 01:12:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!