$ q.all的Jasmine单元测试

时间:2015-02-19 14:12:19

标签: angularjs jasmine

我的控制器如下:

$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

有人可以帮我解决此错误。

Thans

1 个答案:

答案 0 :(得分:0)

如果您真的想测试返回值,则必须为每个服务创建一个Jasmine间谍对象。每个间谍对象都可以模拟一个特定的方法(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);
  });
});