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

前端 未结 4 988
面向向阳花
面向向阳花 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:38

    something along these lines / with sinon and jQuery deferreds

    ajaxStub = sinon.stub($, "ajax");
    
    function okResponse() {
      var d = $.Deferred();
      d.resolve( { username: "testuser", userid: "userid", success: true } );
      return d.promise();
    };
    
    function errorResponse() {
     var d = $.Deferred();
     d.reject({},{},"could not complete");
     return d.promise();
    };
    
    ajaxStub.returns(okResponse());
    ajaxStub.returns(errorResponse());
    

提交回复
热议问题