4

My controller looks like:

$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];
});

I tried to follow this How to resolve $q.all promises in Jasmine unit tests?

But in my case its give error like

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

$q.all expects an Array of Promises, and if they aren't Promises they will be considered immediately completed. so I used resources with $promise. I got it from here

Angular Resource calls and $q

Can someone help me how to fix this error.

Thans

Community
  • 1
  • 1
troy
  • 997
  • 4
  • 13
  • 27

1 Answers1

0

If you would actually like to test the return values, you must create a Jasmine spy object for each service. Each spy object can mock a particular method (queryAll) and then return some test data when the promise resolves.

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);
  });
});
Nuri Hodges
  • 868
  • 6
  • 13