在测试中等待 stateChange
Wait for stateChange in test
我的控制器中有一个范围函数和一些异步函数。一切都完成后,它会改变状态。
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');
});
});
...
您可以使用
$q.all.(promises).then(
function(){
$state.go()
});
等待你的任务完成,只要你能把它们包装在一个承诺中。
更多信息here。
当我编辑问题来描述我的问题时,我找到了解决方案。
可以监听广播事件,所以可以使用
...
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');
});
});
...
我的控制器中有一个范围函数和一些异步函数。一切都完成后,它会改变状态。
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');
});
});
...
您可以使用
$q.all.(promises).then(
function(){
$state.go()
});
等待你的任务完成,只要你能把它们包装在一个承诺中。
更多信息here。
当我编辑问题来描述我的问题时,我找到了解决方案。 可以监听广播事件,所以可以使用
...
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');
});
});
...