javascript - Jasmine Jquery Spy AJAX完整功能

标签 javascript jquery unit-testing jasmine jasmine-jquery

我正在尝试编写单元测试来覆盖方法 Acomplete() block 。我可以使用 Deferred 模拟 ajax 请求。但 Deferred 不支持 Complete() 所以我收到以下错误 TypeError: _this.methodB(...).complete 不是一个函数。请帮助我覆盖 methodB(..).complete() block 。

    methodB: function(xURL, container) {
    var _this = this;
    return $.ajax({

    type: 'GET',
    url: xURL,
    async: false,
    dataType: 'html',
    timeout: _this.ajaxTimeOut
    })
    .fail(function(resp) {
    _this.doSomethingOnFail();
    })
    .done(function(resp, textStatus, jqXHR) {
        if (jqXHR.status === 200 && resp !== '') {
           _this.doSomethingOnDone();       
     }              
  });
},
    methodA: function(e) {
    var _this = this,
   _this.methodB(_this.refineURL, _this.$el)
   .complete(function(resp) {
    **if (resp.responseText !== undefined && 
        resp.responseText.indexOf("PRICE_DATA_AVLBL = 'false'") > -1) {
        var params1 = _this._getFilterURLParameters(_this.refineURL);
        var params2 = _this._getFilterURLParameters(_this.SUCC_URL);

        if (params1.lowerbound !== params2.lowerbound || 
            $(e.currentTarget).hasClass('js-txt-min')) {
            $txtMin.addClass('border-danger');
        } else {
            $txtMin.val(params2.lowerbound);
        }
    } else {
       _this._pageSubmit();
    }**

 });

}

单元测试代码:

  it('validate ajax complete', function ajaxComplete(){
      spyOn($, 'ajax').and.callFake( function fake() {
      XMLHttpRequest = jasmine.createSpy('XMLHttpRequest');      
      var jqXHR = new XMLHttpRequest();
      jqXHR.status = 200;
      var dea = new $.Deferred();    
      dea.resolve('{property:value}',' ', jqXHR);
      return dea;
   });
   f.methodA();
  });

最佳答案

模拟依赖项

重要的是要记住,在测试函数时,您会模拟该函数的依赖关系。您不想在测试中实际调用这些依赖函数,因为您没有测试这些函数。您应该在其他地方测试这些函数,并模拟它们的依赖关系等。

您的代码

在测试 methodA 时牢记这一点,您不应该关心 methodB 发出 ajax 请求。您所关心的只是它返回某个具有完整功能的对象,以及您正确连接回调等。

测试

以下(未经测试的)代码应该大致适合您,或者为您提供一个不错的起点。

describe('.methodA()', function() {
  var methodBResult;

  beforeEach(function() {
    methodBResult = jasmine.createSpyObj('result', ['complete']);
    spyOn(f, 'methodB').and.returnValue(methodBResult);
  });

  it('should call .methodB()', function() {
    f.refineURL = 'something for the test';
    f.$el = 'something else for the test';
    f.methodA();
    expect(f.methodB.calls.count()).toBe(1);
    expect(f.methodB).toHaveBeenCalledWith(f.refineURL, f.$el);
  });

  it('should register a callback on complete', function() {
    f.methodA();

    expect(methodBResult.complete.calls.count()).toBe(1);
    expect(methodBResult.complete).toHaveBeenCalledWith(jasmine.any(Function));
  });

  it('should call .doSomethingOnComplete() when the callback is invoked', function() {
    spyOn(f, 'doSomethingOnComplete');

    f.methodA();

    var callback = methodBResult.complete.calls.argsFor(1)[0];    
    callback();

    expect(f.doSomethingOnComplete.calls.count()).toBe(1);
    expect(f.doSomethingOnComplete).toHaveBeenCalledWith();
  });
});

关于javascript - Jasmine Jquery Spy AJAX完整功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027706/

相关文章:

javascript - 无法在具有模态 : true 的对话框中选择 jquery 多选过滤器

javascript - 在 jQuery 表绑定(bind)中获取更多数据时,如何在表主体中保留旧数据?

javascript - 渲染函数(reactjs)出现错误?

jquery - 在 ('click' 上)不工作?

javascript - 一个 switch 语句中包含多个表达式

javascript - 在后退按钮 IE11 上触发 document.ready

javascript - jQuery UI Accordion + Cookies - 默认关闭?

python - 如何调试通过单元测试部分覆盖但在重用时产生错误结果的 Python 代码?

asp.net - 您将如何交换连接字符串来访问测试数据库以进行单元测试?

angular - 单元测试因 Angular 中的 NullInjectorError 而失败