2017-05-08 32 views
0

測試文件:

describe('$rootScope', function() { 
    describe('$on', function() { 
     var credentials = "Basic abcd1234"; 
     var $scope; 
     var $rootScope; 
     var $httpBackend; 
     ... 
     beforeEach(inject(function($injector, $controller, _$rootScope_, $state, _$q_, currentUserService) { 
      $scope = _$rootScope_.$new(); 
      $rootScope = _$rootScope_; 
      $httpBackend.when('GET', 'dist/app/login/login.html').respond({'title': 'TEST_TITLE'}, {'A-Token': 'xxx'}); 
     })); 

     ... 
     it('should set $scope.title if noAuthorization', function() { 
      spyOn($rootScope, '$on'); 
      $controller('AppCtrl', {$scope: $scope}); 
      $rootScope.$broadcast("$stateChangeStart"); 
      $rootScope.$apply(); 

      expect($rootScope.$on).toHaveBeenCalled(); 
      expect($scope.title).toBe('TEST_TITLE'); 

     }); 
    }); 
}); 

$ scope.title在我的測試中總是不確定的。期望總是失敗。我試過$ emit,$ apply等等。這是在一個控制器內,在$ rootScope.on方法中。

但是,如果我在js文件內部登錄$ scope.title,它確實顯示$ scope.title已被更新。

我還要提到的是被調用的函數是不是在$範圍,即它不是$scope.updateTitle,它只是function updateTitle(...)

我不覺得實際的代碼是必要的證明,因爲它做它的工作。我只是想知道爲什麼測試中的$範圍沒有得到更新。

回答

-1

簡而言之:不要忘記.andCallThrough()的間諜。茉莉間諜需要andCallThrough()。使用element.scope()訪問正確的範圍。

spyOn(scope, '$apply').andCallThrough(); 
+0

沒有運氣。它什麼都不做。我把一個callThrough(()用於$ on,$ apply,仍然未定義。 – Tai