【问题标题】:$stateChangeSuccess always being triggered in Unit Test$stateChangeSuccess 总是在单元测试中触发
【发布时间】:2016-01-14 15:31:56
【问题描述】:

在我的控制器中,我在 $scope 上有两个事件监听器,一个用于 $stateChangeSuccess,一个用于消息事件:

$scope.$on('$stateChangeSuccess', function () {
  $scope.methodA();
});

$scope.$on('message', function () {
  $scope.methodB(); 
});

在我的单元测试中,我只想测试 methodB 是否已被调用:

spyOn($scope, '$on').and.callThrough();
spyOn($scope, 'methodB');
$scope.$emit('message');
expect($scope.methodB).toHaveBeenCalled();

问题是 $stateChangeSuccess 也被调用,即使我自己没有发出事件。是这种情况还是我在 ui-router 中配置错误?

我可以通过模拟 $stateChangeSuccess 事件来解决这个问题,但我宁愿在我的单元测试中根本不调用它,除非我自己发出事件。

有什么想法吗?

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-runner


    【解决方案1】:

    我设法使用this question 的第二个答案解决了这个问题。

    基本上,您可以通过在 $urlRouterProvider 模块上调用 deferIntercept() 在单元测试中禁用 ui-router。

    beforeEach(module(function($urlRouterProvider) {
      $urlRouterProvider.deferIntercept();
    }));
    

    这个和其他与 karma/jasmine 相关的 ui-router 问题在here 进行了解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多