我有一个控制器:
myApp.controller('someCtrl', function ($scope, myAsyncService, $routeParams) {
var foo_id = $routeParams.foo_id;
$scope.foo = 0;
$scope.bar = false;
$scope.$on('that_happened',
function (event, plan) {
myAsyncService.save({id: foo_id}).$promise.then(function (res) {
$scope.bar = true;
$location.path('/foo/' + res.id);
});
}
);
});
发出“that_happend”事件后,服务调用异步方法,我想测试 $scope 并在执行回调后更改位置:
describe('my module', function () {
var res_mock = 2,
myAsyncService_mock = {
save: function () {}
};
describe('someCtrl', function(){
var $location,
$scope,
$subscope,
deferred,
promise_mock,
ctrl,
$q;
beforeEach(
inject(function ($rootScope, _$location_, _$q_) {
$q = _$q_;
$location = _$location_;
$scope = $rootScope.$new();
$subscope = $scope.$new();
deferred = $q.defer();
promise_mock = {
$promise: deferred.promise
};
spyOn(myAsyncService_mock, 'save').andReturn(promise_mock);
ctrl = $controller('someCtrl',
{
$scope: $scope,
$location: $location,
myAsyncService: myAsyncService_mock
}
);
})
);
it('should call save method of service and set bar to true and goto /foo/:saved_foo.id ', function () {
var saved_foo_mock = {
id: 3
}
$scope.foo = 11;
$scope.bar = false;
$subscope.$emit('that_happened');
deferred.resolve(saved_foo_mock);
expect(myAsyncService_mock.save).toHaveBeenCalled();
expect($scope.bar).toBe(true);
expect($location.path()).toBe('/foo/' + saved_foo_mock.id);
});
});
});
但是测试失败并出现错误“预期错误为真”。似乎 promise 回调未执行或在 expect() 之后执行;
我尝试以异步方式对其进行测试,但结果是相同的 - 测试因超时而失败:
runs(function () {
$scope.bar = false;
$subscope.$emit('that_happened');
});
waitsFor(function () {
deferred.resolve(saved_foo_mock);
return $scope.bar;
}, 'bar should be true', 500);
runs(function () {
expect(myAsyncService_mock.save).toHaveBeenCalled();
expect($location.path()).toBe('/foo/' + saved_foo_mock.id);
});
这是怎么回事?为什么 $scope 和位置路径没有改变?