Corner JS router: ui-sref test

I am trying to check out some views that use <a ui-sref='someState'>link</a> to communicate with other states in my application. In my tests, I start clicking on these elements as follows:

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

How can I check if the state is switched to someState ? Using $state in my controller would be easy:

 // 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 which object to spy on. How can I verify that my application is in the correct state?

+7
angularjs angular-ui-router jasmine
source share
3 answers

I found it myself. After looking at the source code of angular ui router, I found this line inside the 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(); } }); 

When an item receives a click, $state.go ends with a call to $timout . So, in your tests you need to introduce the $timeout module. Then just do $timeout.flush() like this:

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

You can use:

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

Hope this helps

0
source share

I think you need to use $ rootScope. $ apply () to change state.

0
source share

All Articles