Angularjs:测试控制器功能,改变$scope
我正在尝试测试此控制器功能:Angularjs:测试控制器功能,改变$scope,angularjs,testing,jasmine,Angularjs,Testing,Jasmine,我正在尝试测试此控制器功能: $scope.deleteAccount = function(account) { Account.deleteAccount(account._id) .then(function() { angular.forEach($scope.accounts, function(a, i) { if (a === account) { $scope.accounts.splice(i, 1); } })
$scope.deleteAccount = function(account) {
Account.deleteAccount(account._id)
.then(function() {
angular.forEach($scope.accounts, function(a, i) {
if (a === account) {
$scope.accounts.splice(i, 1);
}
});
})
.catch(function(err) {
$scope.errors.other = err.message;
});
};
它位于管理页面上。该函数使用promise调用工厂,工厂将删除服务器上的帐户。然后,该函数删除作用域中的元素,以便不再显示已删除的元素
我的测试是这样的:
beforeEach(inject(function ($controller, $rootScope, _$location_, _$httpBackend_) {
$scope = $rootScope.$new();
$location = _$location_;
$httpBackend = _$httpBackend_;
fakeResponse = '';
AdminAccountCtrl = $controller('AdminAccountCtrl', {
$scope: $scope
});
$location.path('/admin/account');
}));
it('test delete account', function () {
expect($location.path()).toBe('/admin/account');
$httpBackend.expectGET('/api/accounts').respond([{_id: 1}, {_id: 2}, {_id: 3}]);
$httpBackend.when('GET', 'app/admin/admin.account.html').respond(fakeResponse);
$httpBackend.when('DELETE', '/api/accounts/1').respond(fakeResponse);
$httpBackend.flush();
$scope.deleteAccount($scope.accounts[0]);
expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);
});
可悲的是,结果是:
Expected [ { _id : 1 }, { _id : 2 }, { _id : 3 } ] to equal [ { _id : 2 }, { _id : 3 } ].
尝试在deleteAccount之后调用$scope.$digest。这是必需的,因为测试的摘要周期与它在浏览器中正常运行的方式不同
$scope.deleteAccount($scope.accounts[0]);
$scope.$digest();
expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]);
和你的问题是什么?第一个元素没有被删除-测试失败。我想知道为什么阵列没有改变。谢谢你的回复,但我担心它不起作用。我还尝试监视函数和$scope。$apply,但错误仍然存在。可能您还需要移动$httpBackend.flush,以便在deleteCountMoving the flush not work account未定义之后运行。但在deleteCount成功后第二次调用flush。所以非常感谢你$httpBackend.when'DELETE','/api/accounts/1'。respondFakerResponse$httpBackend.flush$scope.deleteCount$scope.accounts[0]$httpBackend.flush```