AngularJS ui-router:测试ui-sref

前端之家收集整理的这篇文章主要介绍了AngularJS ui-router:测试ui-sref前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试测试一些使用< a ui-sref ='someState'> link< / a>的视图.链接到我的应用程序中的其他状态.在我的测试中,我触发了对这些元素的点击,如下所示:
element.find('a').click()

如果状态切换到某个状态,我该如何测试?在我的控制器中使用$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时,我不知道要监视什么对象.如何验证我的应用程序处于正确状态?

我自己找到了.在查看了角度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);
原文链接:https://www.f2er.com/angularjs/143653.html

猜你在找的Angularjs相关文章