【问题标题】:Simulating an Empty Array Response from an HTTP Post Request using Karma使用 Karma 模拟来自 HTTP Post 请求的空数组响应
【发布时间】:2016-12-23 11:35:11
【问题描述】:

我正在使用 Karma 测试我的 MEAN 应用程序,并且在从 AngularJS (ng-mock) 中的 $httpBackend 'expectPOST' 方法返回空数组时遇到困难。

这是我正在测试的服务方法:

  this.getIds = function(path, callback) {
    // console.log('Sending request to get IDs to the path: ' + path);
    $http.post('/dropbox/getIds', {path: path} ).success(function(items) {
      if(items.error !== undefined) {
        console.log(items.error);
        callback('Error with Dropbox API files list request'); // Do not alter string
        return;
      }
      var empty = (items.length === 0) ? true : false;
      callback(items, empty);
    }).error(function(err) {
      console.log(err);
      callback('Error making ID request');
    });
  };

这里是单元测试代码sn-p:

it('should request Dropbox file IDs at a give path - no errors but empty response', function() {
  $httpBackend.expectPOST("/dropbox/getIds").respond({ data: [] });
  dropboxService.getIds('path', function(items, empty) {
    expect(items).to.deep.equal({data: []});
    expect(empty).to.deep.equal(true);
  });
});

此测试中的“空”变量应为真,因为 HTTP POST 响应是一个空的“数据”数组,但测试失败,因为“空”变量实际上为假。

谁能告诉我我做错了什么,无论是在测试代码还是服务方法本身?

【问题讨论】:

    标签: javascript angularjs arrays unit-testing karma-runner


    【解决方案1】:

    编辑:

    根据 Angular 文档 (https://docs.angularjs.org/api/ng/service/$http),您处理回调返回的方式不正确。在您的测试中,项目将是

    {
      data: { data: [] } }
    }
    

    我认为你的三元应该是这样的

    var empty = (items.data.data.length === 0) ? true : false;
    

    然后,您需要将您的第一个断言更改为

    expect(items.data).to.deep.equal({data: []});
    

    原帖不正确:

    您需要调用有关承诺解决范围的摘要。它应该看起来像这样:

    let scope;
    beforeEach(() => {
      inject($rootScope => {
        scope = $rootScope.$new();
      });
    });
    
    it('should request Dropbox file IDs at a give path - no errors but empty response', function(done) {
      $httpBackend.expectPOST("/dropbox/getIds").respond({data: []});
      dropboxService.getIds('path', function(items, empty) {
        expect(items.data).to.deep.equal({data: []});
        expect(empty).to.deep.equal(true);
        done();
      });
      scope.$digest();
    });
    

    【讨论】:

    • 这不起作用并且不能解决问题。我有其他有回调的测试,我的测试工作正常。问题是模拟一个空数组,而不是解决回调。如果您需要证明,我对此方法还有其他测试,其中返回完整的数组并且这些测试有效。
    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2023-04-05
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    相关资源
    最近更新 更多