【问题标题】:Jasmine unit test for $q.all$q.all 的 Jasmine 单元测试
【发布时间】:2015-02-19 14:12:18
【问题描述】:

我的控制器看起来像:

$q.all([test1Factory.queryAll().$promise, test2Factory.queryAll().$promise,test3Factory.queryAll().$promise]).then(function(results) { 
   $scope.testList1 = results[0];
   $scope.testList2 = results[1];
   $scope.testList3 = results[2];
});

我试着关注这个How to resolve $q.all promises in Jasmine unit tests?

但在我的情况下,它会出现类似

的错误
TypeError: 'undefined' is not an object (evaluating 'test1Factory.queryAll().$promise')

$q.all 需要一个 Promise 数组,如果它们不是 Promise,它们将被视为立即完成。所以我使用了 $promise 的资源。我是从这里得到的

Angular Resource calls and $q

谁能帮我解决这个错误。

【问题讨论】:

  • 奇怪,我的延迟对象上没有$promise。你试过promise吗?
  • 不,我尝试使用 promise 而不是 $promise ...这些值未定义..

标签: angularjs jasmine


【解决方案1】:

如果您真的想测试返回值,您必须为每个服务创建一个 Jasmine 间谍对象。每个 spy 对象都可以模拟一个特定的方法(queryAll),然后在 promise 解决时返回一些测试数据。

describe('$q.all', function() {
  beforeEach(function() {
    return module('yourNgModule');
  });
  beforeEach(inject(function($injector) {
    var ctrl, q, rootScope, scope, test1Factory, test2Factory, test3Factory;
    q = $injector.get('$q');
    rootScope = $injector.get('$rootScope');
    scope = rootScope.$new();
    test1Factory = jasmine.createSpyObj('test1Factory', ['queryAll']);
    test2Factory = jasmine.createSpyObj('test2Factory', ['queryAll']);
    test3Factory = jasmine.createSpyObj('test3Factory', ['queryAll']);
    test1Factory.queryAll.and.returnValue(q.when(1));
    test2Factory.queryAll.and.returnValue(q.when(2));
    test3Factory.queryAll.and.returnValue(q.when(3));
    ctrl = $injector.get('$controller').controller('yourNgController', {
      $scope: scope,
      $q: q,
      test1Factory: test1Factory,
      test2Factory: test2Factory,
      test3Factory: test3Factory
    });
    rootScope.$digest();
  }));
  return it('returns values for all promises passed to $q.all', function() {
    expect(scope.testList1).toEqual(1);
    expect(scope.testList2).toEqual(2);
    expect(scope.testList3).toEqual(3);
  });
});

【讨论】:

    猜你喜欢
    • 2013-04-25
    • 2017-04-04
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多