gpt4 book ai didi

Angularjs:测试 Controller 功能,它改变了 $scope

转载 作者:行者123 更新时间:2023-11-28 20:54:33 25 4
gpt4 key购买 nike

我正在尝试测试这个 Controller 功能:

$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}]);

关于Angularjs:测试 Controller 功能,它改变了 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com