Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ui-router causing "full page reload" in controller test?

I'm trying to write some angular controller tests but ran into:

Some of your tests did a full page reload!

karma/jasmine error as soon as my test ran httpMock.flush()

After troubleshooting by removing code from my controller and it's corresponding test piece by piece until it passed, I discovered that the test would pass if I removed $state dependency so the error was somehow related to ui-router.

After more digging it appears to be related to the inclusion of $urlRouterProvider in my routes file:

App.config(function($stateProvider, $urlRouterProvider) {
 // For any unmatched url, redirect to
 $urlRouterProvider.otherwise('dashboard');

$urlRouterProvider produces window.location. If I remove $urlRouterProvider.otherwise line, I can put back $state and the tests pass.

EDIT:

After more digging.

I did end up finding that we were doing a full page redirect somewhere else in $rootScope.$on('$stateChangeStart') checking to see if a cookie existed or to log the user out.

But even upon commenting that out, I get a new error: unexpected GET request for the template of the dashboard view. I figured maybe my test doesn't pass any values to the ui-router mechanism (I was just passing $state through) so it doesn't know what the state is and therefore triggers the $urlRouterProvider.otherwise route. So I added a state.transitionTo('base.settings.sales-channels.edit', {channelId:1}); in my test. This is a nested state.

This indeed changes the error message to Error: Unexpected request: GET ../src/settings/index.tpl.html, which looks like it's the template for the parent state since settings comes before sales-channels, which comes before edit in my state name.

Why do I get this error? Do we have to mock out expectations for all the parent state's templates?

EDIT

Here is a plunkr the reproduces the test error I am getting http://plnkr.co/edit/DoaIBqK1JMqbTJj3vlmH?p=preview

EDIT

Looks like the template GET request is a known issue: https://github.com/angular-ui/ui-router/issues/212

I implemented the state mock method mentioned in that issue and the unit tests pass now.

like image 250
Homan Avatar asked Nov 11 '22 15:11

Homan


1 Answers

I'd argue that your test isn't focused enough and you are actually testing ui-router instead of your own code. For example, I'd test your controller in isolation, probably asserting that your controller is exposing the appropriate values or api.

Nonetheless, you can stub out the view expectations to satisfy the $templateCache calls ui-router will make to traverse to your nested state. I fiddled with your code here and tests pass: http://plnkr.co/edit/hjw599oXGCjY03nbVpSN?p=preview

like image 115
SonOfNun Avatar answered Nov 15 '22 12:11

SonOfNun