茉莉花间谍和解决承诺

时间:2016-01-08 16:04:56

标签: javascript angularjs unit-testing karma-jasmine

我正在测试一个使用返回promise的服务的控制器。我在测试中模拟了一个服务并创建了一个spy,以便我可以测试服务是否实际被调用。

但是我一直收到此错误

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

我的测试

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();
});

1 个答案:

答案 0 :(得分:1)

对于Jasmine 2,您必须使用

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

而不是andReturn()

Read the docs。如果您要从Jasmine 1迁移到Jasmine 2,您也可能需要read this