vlapo21
vlapo21

Reputation: 344

ui-router test failed with event.preventDefault() in $stateChangeStart

I have problem with my angular test.

describe('Routes test', function() {
    //Initialize global variables
    var $state,
        $location;

    // Load the main application module
    beforeEach(module("MyApp"));

    beforeEach(inject(function(_$location_, _$state_, $templateCache) {
        $state = _$state_;
        $location = _$location_;

        // We need add the template entry into the templateCache if we ever
        // specify a templateUrl
        $templateCache.put('signin.admin.view.html', 'signin');
    }));

    it('should be redirect to signin if user is not loggedin', function() {
        $rootScope.$apply(function() {
            $location.path('/');
        });
        expect($state.current.name).toEqual('signin');
        console.log($state.current);
    });
});

So I expect signin state because user is not logged in. But from console $state.current is still:

Object{name: '', url: '^', views: null, abstract: true}

To redirect I used this code:

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if (toState.name.indexOf('signin') === 0 ) {
        if( loggedIn ) {
            event.preventDefault();
            $state.go('layout.dashboard');
        }
    } else {
        if( !loggedIn ) {
            event.preventDefault();
            $state.go('signin');
        }
    }
});

Variable loggedIn is false. So I dont understand, when I make test manually in browser $state.current is as expected. But not in this test.

Thank you for your help.

Upvotes: 1

Views: 504

Answers (1)

fshaw1
fshaw1

Reputation: 366

Rather than doing $rootScope.$apply(...) try doing:

$location.path('/');
$rootScope.$broadcast('$locationChangeSuccess');

UI Router listens to the $locationChangeSuccess event that is fired from angular's $location service. When it catches this event it will find the correct state and begin navigating to that state, hence firing the $stateChangeStart event.

Hope this helps!

Upvotes: 1

Related Questions