【问题标题】:Wait for stateChange in test在测试中等待 stateChange
【发布时间】:2016-08-16 15:17:09
【问题描述】:

我的控制器中有一个范围函数和一些异步函数。一切完成后,它会改变状态。

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

...

【问题讨论】:

  • 你的问题不清楚。您想知道如何在所有异步函数执行完毕后等待,以便更改状态,或检测状态何时完成更改?

标签: javascript angularjs karma-mocha


【解决方案1】:

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

...

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

...

【讨论】:

    【解决方案2】:

    你可以使用

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

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

    更多信息here.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      相关资源
      最近更新 更多