Search code examples
javascriptangularjskarma-mocha

Wait for stateChange in test


I have a scope function in my controller with some async functions. After everything is done it changes the state.

controller.js

$scope.test = function () {
    async().then(function () {
        $state.go('somewhere');
    });
};

I could test it with setTimeout() but thats dirty I think.

How do I wait for the stateChange in my test?

Edit:

I want to write unit tests for the test() function but as it is no promise I need to watch for the state change in the test. But how? It works with setTimeout() but I don't want to use setTimeout() because it just doesn't feel right. Is there something like $scope.$watch for states?

test.js

...

it('test()', function (done) {
    $scope.test();
    setTimeout(function () { // I want this replaced with a listener for state
        expect($scope.someVar).to.be.equal('value');
        expect($state.current.name).to.be.equal('somewhere');
    });
});

...

Solution

  • As I was editing the question to describe my problem I found the solution. It's possible to listen for broadcasted events so it's possible to use

    ...
    
    it('test()', function (done) {
        $scope.test();
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            expect($scope.someVar).to.be.equal('value');
            expect(toState.name).to.be.equal('somewhere');
        });
    });
    
    ...