AngularJS ui-router: Test ui-sref

别说谁变了你拦得住时间么 提交于 2019-11-30 13:50:27

I found it myself. After having a look into the angular ui router source code, I found this line inside the ui-sref directive:

// 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();
  }
});

When the element receives a click, the $state.go is wrapped in a $timout callback. So, in your tests, you have to inject the $timeout module. Then just do a $timeout.flush() like this:

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

You can use :

[...]
element.find('a').click()
expect($state.is('someState')).toBe(true)

Hope this helps

I think you need to use $rootScope.$apply() in order to have the state change.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!