2016-08-05 85 views
0

我有兩個控制器和一個服務。在第一個控制器中,我訂閱了一個事件來做一些事情。第二個控制器執行一些操作,並在完成時廣播該事件。請參閱下面的示例,超時僅用於模擬長時間運行的操作。我想測試hasLoaded設置爲true使用Jasmine 2.0請指教。如何測試使用Jasmine在回調中執行的操作

var myApp = angular.module('MyApp', []); 
 

 
myApp.controller('MyCtrl1', ['$scope', 'myService', function($scope, myService) { 
 
    $scope.hasLoaded = false; 
 
    $scope.fileName = ''; 
 
    
 
    myService.onLoaded($scope, function(e, data){ 
 
     // I want to test the following two lines, in the really the code here is much more complex 
 
     $scope.fileName = data.fileName; 
 
     $scope.hasLoaded = true; 
 
    }); 
 
}]); 
 

 
myApp.controller('MyCtrl2', ['$rootScope', '$scope', '$timeout', 'myService', function($rootScope, $scope, $timeout, myService) { 
 
    $scope.isLoading = false; 
 
    $scope.title = 'Click me to load'; 
 

 
    $scope.load = function(){ 
 
     $scope.isLoading = true; 
 
     $scope.title = 'Loading, please wait...'; 
 
     
 
     $timeout(function() { 
 
      $rootScope.$emit('loaded', { fileName: 'test.txt'}); 
 
     }, 1000); 
 
    }; 
 

 
    myService.onLoaded($scope, function(){ 
 
     $scope.hasLoaded = true; 
 
    }); 
 
}]); 
 

 
myApp.service('myService', ['$rootScope', function ($rootScope) { 
 
    this.onLoaded = function(scope, callback) { 
 
     var handler = $rootScope.$on('loaded', callback); 
 
     scope.$on('$destroy', handler); 
 
    }; 
 
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> 
 

 
<div ng-app="MyApp"> 
 
    <div ng-controller="MyCtrl1"> 
 
     <div ng-show="hasLoaded">{{fileName}} loaded !!!</div> 
 
    </div> 
 
    <div ng-controller="MyCtrl2"> 
 
     <button ng-click="load()" ng-hide="hasLoaded" ng-disabled="isLoading" ng-bind="title"></button> 
 
    </div> 
 
</div>

更新:我已經加入到參數廣播呼叫,使其更接近我的情況。

回答

2

你真的應該分別測試你的每件作品(控制器和服務)。在你的情況下,對於設置hasLoaded控制器測試正常真的只需要測試與正確的服務和回調您的註冊做你所期望的:

it("should register with the service and do the right thing when the callback is executed", inject(function ($controller, $rootScope, myService) { 
     var $scope = $rootScope.$new(); 
     spyOn(myService, 'onLoaded').and.callThrough(); 

     var ctrl = $controller('MyCtrl1', {$scope: $scope, myService: myService}); 
     $scope.$apply(); 

     //verify that the controller registers its scope with the service 
     expect(myService.onLoaded).toHaveBeenCalledWith($scope, jasmine.any(Function)); 
     //now call the callback that was registered to see if it sets the property correctly 

     var mockData = { 
      fileName: 'some file name' 
     }; 
     myService.onLoaded.calls.argsFor(0)[1]('loaded', mockData); 
     expect($scope.hasLoaded).toBeTruthy(); 
     expect($scope.fileName).toBe("some file name"); 
    })); 

爲您服務,其他然後編寫測試控制器分開。

+0

謝謝,這是我需要的。你能告訴我爲什麼我們需要$ scope。$ apply();呼叫? – Antipod

+0

你實際上不是你的情況。我只是習慣於這樣做,因爲最近我一直在測試模擬promise,需要$ apply()才能在測試中解決。 – mcgraphix