2015-05-29 78 views
0

我的控制器:功能沒有被稱爲有因果報應spyOn

window.map.controller('ScheduleHomeController', ['$scope', '$location', '$route', '$routeParams', 'cache', 'patientCache', 
    function($scope, $location, $route, $routeParams, cache, patientCache) { 

     cache.set('ui', 'headerMessage', ''); 

     if(cache.get('patient', 'currentPatient').patientId !== $routeParams.patientId) { 
      cache.set('patient', 'currentPatient', patientCache.getPatient(parseInt($routeParams.patientId, 10))); 
     } 

     switch($route.current.originalPath) { 
      case '/patients/:patientId/schedule': 
       cache.set('ui', 'schedulePage', 'daily-schedule'); 
       $scope.showScheduleNavbar = true; 
       break; 
      default: 
       $scope.showScheduleNavbar = false; 
       break; 
     } 
    } 
]); 

我的測試是:

fdescribe('ScheduleHomeController', function() { 
    var scope, cache, $route, patientCache, $routeParams; 

    beforeEach(function() { 
     module('mapApp'); 

     return inject(function($injector) { 
     var $controller, $rootScope; 
     $rootScope = $injector.get('$rootScope'); 
     $controller = $injector.get('$controller'); 
     $route = $injector.get('$route'); 
     cache = $injector.get('cache'); 
     patientCache = $injector.get('patientCache'); 
     $routeParams = $injector.get('$routeParams'); 

     scope = $rootScope.$new() 
     $route.current = { originalPath: '/patients/:patientId/schedule' }; 

     $controller('ScheduleHomeController', { 
      $scope: scope, 
      cache: cache, 
      patientCache: patientCache, 
      $route: $route, 
      $routeParams: $routeParams 
     }); 

     return scope.$digest(); 

     }); 
    }); 

    it('should set the ui.headerMessage to empty', function() { 
     spyOn(cache, 'set'); 
     expect(cache.set).toHaveBeenCalledWith('ui', 'headerMessage', ''); 
    }); 

}); 

因此,我希望cache.set被調用,而是我得到Expected spy set to have been called with [ 'ui', 'headerMessage', '' ] but it was never called.

我做錯了什麼?

回答

2

你必須在函數執行之前(在控制器初始化中)執行spyOn cache.set。所以把它放在$ contorller之前:

... 
spyOn(cache, 'set'); 
$controller('ScheduleHomeController', { 
...