简体   繁体   中英

Jasmine spy and resolving promises

I am testing a controller that uses a service that returns a promise. I have mocked out a service in my tests and created a spy so that I can test if the service was actually called.

However I keep getting this error

TypeError: 'undefined' is not a function 
    (evaluating 'spyOn(mockService, 'one').andReturn(deferred.promise)')

My Test

beforeEach(inject(function($rootScope, $controller, $q) {
  scope = $rootScope.$new();

  mockService = {
    one: function(){
      // mock promise
      var deferred = $q.defer();
      deferred.resolve([
        //my array
      ]);
      return deferred.promise;
    },
    two: function(){
      // mock promise
      var deferred = $q.defer();
      deferred.resolve([
        //my data
      ]);
      return deferred.promise;
    }
  }
  var deferred = $q.defer();
  spyOn(mockService, 'one').andReturn(deferred.promise);

  controller = $controller('MyCtrl', {
    $scope: scope,
    mockService: mockService
  });
}));

it('should call mockService service', function(){
  //causes promises to check to see if they are fulfilled
  scope.$digest();
  expect(mockService.one).toHaveBeenCalled();
});

For Jasmine 2 you must use

spyOn(mockService, 'one').and.returnValue(deferred.promise);

instead of andReturn() .

Read the docs . If you're migrating from Jasmine 1 to Jasmine 2, you also might want to read this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM