小编典典

AngularJS ui路由器:测试ui-sref

angularjs

我正在尝试测试一些视图,这些视图<a ui- sref='someState'>link</a>用于链接到应用程序中的其他状态。在我的测试中,我触发了对此元素的点击,如下所示:

element.find('a').click()

如果状态切换为,该如何测试someState$state在我的控制器中像这样使用时,这很容易:

// in my view
<a ng-click="goTo('someState')">link</a>

// in my controller
$scope.goTo = function(s) {
  $state.go(s)
};

// in my tests
spyOn($state, 'go');
element.find('a').click()
expect($state.go).toHaveBeenCalled()

但是当我使用时,我ui-sref不知道要监视什么对象。如何验证我的应用程序处于正确状态?


阅读 315

收藏
2020-07-04

共1个答案

小编典典

我自己找到的。在查看了角度ui路由器源代码后,我在ui-sref指令中找到了以下行:

// angular-ui-router.js#2939
element.bind("click", function(e) {
  var button = e.which || e.button;
  if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
    // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
    $timeout(function() {
      $state.go(ref.state, params, options);
    });
    e.preventDefault();
  }
});

当元素收到点击时,$state.go会包装在$timout回调中。因此,在测试中,您必须注入$timeout模块。然后$timeout.flush()像这样做:

element.find('a').click();
$timeout.flush();
expect($state.is('someState')).toBe(true);
2020-07-04