我的主控制器中有一个简单的函数,可基于ui.router的$scope.loading
和$stateChangeStart
事件更新$stateChangeSuccess
。
$scope.$on('$stateChangeStart', function(event, toState) {
if (toState.resolve) {
$scope.loading = true;
}
});
$scope.$on('$stateChangeSuccess', function(event, toState) {
if (toState.resolve) {
$scope.loading = false;
}
});
在我尝试进行单元测试之前,这非常有用。我找不到触发
$stateChangeSuccess
事件的方法。我的Jasmine单元测试看起来像这样:
it('should set $scope.loading to true', function () {
expect(scope.loading).toBe(false);
$state.go('home');
expect(scope.loading).toBe(true);
scope.$digest();
expect(scope.loading).toBe(false);
});
测试失败,因为
$stateChangeSuccess
从不触发。任何想法将不胜感激。 最佳答案
目前适用于我。
您只需要$broadcast
该事件。请在下面阅读一些伪代码。我希望这可以帮助你。
// Note: this is pseudocode
// controller
// assumes you have your usual setup to support this controller.
// assumes this controller is attached to a component or angular controller.
function myController() {
var vm = this;
vm.isHappy = false;
$scope.$on('$stateChangeSuccess', function(event, toState) {
if (toState.name === 'myState') {
vm.isHappy = true;
}
});
}
// test
// assumes several things
// * ctrl is the currently mocked controller
// * has all the necessary setup & injections (such as $rootScope).
// * testing framework is Jasmine
describe('What happens when I go to my happy place?', function() {
it('should be visible to all that I am happy.', function() {
expect(ctrl.isHappy).toBeFalsy();
$rootScope.$broadcast('$stateChangeSuccess', {
'name': 'myState'
});
// or $scope.$broadcast
expect(ctrl.isHappy).toBeTruthy();
}
});