提供者模拟错误:期待间谍,但得到了函数

时间:2015-08-21 13:46:38

标签: angularjs jasmine karma-jasmine

我对茉莉花很新,我在尝试嘲笑提供者时遇到了一些问题。 我有一个看起来像这样的提供者:

 angular.module('myApp')
 .factory('MyService', function ($resource) {

return {
  actionResource : function(projectId, actionId){
    var url = 'blablabla';
    if(actionId){
        url += "/"+actionId;
    }


    return $resource(url, {}, {
      'create': {
        method: 'POST'
      }
    });
  },
};
});

我有一个使用这个工厂的控制器

angular.module('myApp')

.controller(' myCtrl',function($ scope,MyService,$ state){

$scope.addAction = function(){
    MyService.actionResource($scope.projectId).create($scope.action,
                                   function(){
                                       $state.go('somewhere', {});
                                   });
};

  });

我真的很想测试这个控制器,目前我正在做类似的事情:

'use strict';

describe('[test] [controller] - myCtrl', function() {
  beforeEach(angular.mock.module('myApp'));

 //mock creation
  beforeEach(
       module(function($provide) {
         $provide.factory('MyService', function() {

           var actionResource = function(projectId, actionId){
                                    var create = function(){return {}};
                                    return {create:create};
                                }


           return {actionResource:actionResource}
          }



         )})
       );



  var $httpBackend, $rootScope, myController, mockMyService;

  var scope = {};

  beforeEach(angular.mock.inject(function($injector, $rootScope, MyService) {


       var $controller = $injector.get('$controller');
       scope=$rootScope.$new();
       mockMyService = MyService;


       spyOn(mockPilotageService, 'actionResource').and.callThrough();
       spyOn(mockPilotageService.actionResource(), 'create');

       createController = function() {
       return $controller("myCtrl", {$scope:scope, myService:mockMyService});
     };
   }));




  it('myCtrl - addAction() calls actionRessource.create() method', function() {
      createController();
  scope.addAction();
  expect(mockMyService).toBeDefined();
  expect(mockMyService.actionResource).toHaveBeenCalled();
  expect(mockMyService.actionResource().create).toHaveBeenCalled();

  });


});

我收到此错误:

  

错误:期待间谍,但得到了功能。               在/ Users / ***** / myController.spec.js:86

因此它可以监视mockMyService.actionResource但不能监视mockMyService.actionResource()。create。我不明白为什么

任何帮助都非常受欢迎

谢谢

0 个答案:

没有答案