我的控制器中有一个作用域函数,带有一些异步函数。完成所有操作后,它将更改状态。

controller.js

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


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

如何等待测试中的stateChange?

编辑:

我想为test()函数编写单元测试,但是不能保证我需要注意测试中的状态变化。但是如何?它可与setTimeout()一起使用,但我不想使用setTimeout(),因为它感觉不正确。是否存在类似于$scope.$watch的状态?

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

...

最佳答案

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

...

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

...

10-05 20:44
查看更多