在test中等待stateChange

Wait for stateChange in test

本文关键字:stateChange 等待 test      更新时间:2023-09-26

我有一个范围函数在我的控制器与一些异步函数。当所有操作完成后,它会改变状态。

controller.js

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

我可以用setTimeout()测试,但我认为那很脏。

我如何在测试中等待stateChange ?

编辑:

我想为test()函数编写单元测试,但由于没有承诺,我需要观察测试中的状态变化。但如何?它与setTimeout()一起工作,但我不想使用setTimeout(),因为它只是感觉不对。有类似$scope.$watch的东西吗?

. 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');
    });
});
...

当我在编辑问题来描述我的问题时,我找到了解决方案。可以监听广播事件,所以可以使用

...
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');
    });
});
...

可以使用

$q.all.(promises).then( function(){ $state.go() });

等待你的任务完成,只要你能把它们包装在一个承诺中。