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>
更新:我已经加入到参数广播呼叫,使其更接近我的情况。
谢谢,这是我需要的。你能告诉我为什么我们需要$ scope。$ apply();呼叫? – Antipod
你实际上不是你的情况。我只是习惯于这样做,因为最近我一直在测试模拟promise,需要$ apply()才能在测试中解决。 – mcgraphix