7

I'm trying to test some views, that are using <a ui-sref='someState'>link</a> to link to other states in my application. In my tests I'm triggering a click on this elements like this:

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

How do I test, if the state is switched to someState? It would be easy, when using $state in my controller like this:

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

But when I use ui-sref I don't know what object to spy on. How can I verify, that my application is in the right state?

0

3 Answers 3

18

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, didn't expect this. $timeout.flush() fixes this for the test but you have to remember to do it all the time.
1

You can use :

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

Hope this helps

1 Comment

Thanks for your answer. But this doesn't seem to work, when I look into $state.current the state doesn't switch. Any other ideas?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.