angularjs – 测试ui.router $stateChangeSuccess

前端之家收集整理的这篇文章主要介绍了angularjs – 测试ui.router $stateChangeSuccess前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的主控制器中有一个简单的函数,它根据ui.router的$stateChangeStart和$stateChangeSuccess事件更新$scope.loading.

$scope.$on('$stateChangeStart',function(event,toState) {
  if (toState.resolve) {
    $scope.loading = true;
  }
});
$scope.$on('$stateChangeSuccess',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永远不会触发.任何想法将不胜感激.

解决方法

这对我来说当前有用.

你只需要$播放这个事件.请阅读下面的一些伪代码.我希望这可以帮助你.

// 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',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();
  }
});

猜你在找的Angularjs相关文章