加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 测试ui.router $stateChangeSuccess

发布时间:2020-12-17 16:57:10 所属栏目:安全 来源:网络整理
导读:我的主控制器中有一个简单的函数,它根据ui.router的$stateChangeStart和$stateChangeSuccess事件更新$scope.loading. $scope.$on('$stateChangeStart',function(event,toState) { if (toState.resolve) { $scope.loading = true; }});$scope.$on('$stateChan
我的主控制器中有一个简单的函数,它根据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();
  }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读