【问题标题】:Testing ui.router $stateChangeSuccess测试 ui.router $stateChangeSuccess
【发布时间】:2015-03-20 22:50:37
【问题描述】:

我的主控制器中有一个简单的函数,它根据 ui.router 的 $stateChangeStart$stateChangeSuccess 事件更新 $scope.loading

$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 永远不会触发。任何想法将不胜感激。

【问题讨论】:

  • 你能用这个测试规范特定的每个块之前的祖先更新问题吗?
  • 您不一定需要触发事件,您可以简单地自己调度它。目前尚不清楚与测试用例中的范围相关联的是什么,但scope.$broadcast('$stateChangeStart'); 可能就是您所需要的。您还可以获取$rootScope 并从中广播事件。
  • 我认为scope.$broadcast('$stateChangeStart') 是在正确的轨道上。我很好奇是否需要if (toState.resolve)
  • 感谢@SunilD。能否请您回答问题,以便解决?

标签: angularjs unit-testing jasmine angular-ui-router karma-jasmine


【解决方案1】:

这目前对我有用。

您只需$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();
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-16
    • 2015-05-03
    • 2017-06-14
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多