How to properly unit test jQuery's .ajax() promises using Jasmine and/or Sinon?

前端 未结 4 987
面向向阳花
面向向阳花 2020-12-07 10:59

I\'ve got a fairly straightforward function which returns a jQuery .ajax() promise as such:

CLAW.controls.validateLocation = function(val, $inputEl) {
    re         


        
4条回答
  •  借酒劲吻你
    2020-12-07 11:40

    It is not that complex actually. It suffices to return a promise and resolve it according to your case.

    For example:

    spyOn($, 'ajax').andCallFake(function (req) {
        var d = $.Deferred();
        d.resolve(data_you_expect);
        return d.promise();
    });
    

    for a success, or

    spyOn($, 'ajax').andCallFake(function (req) {
        var d = $.Deferred();
        d.reject(fail_result);
        return d.promise();
    });
    

    for a failure.

    For Jasmine 2.0 the syntax has changed slightly:

    spyOn($, 'ajax').and.callFake(function (req) {});
    

    the method .andCallFake() does not exist in Jasmine 2.0

提交回复
热议问题