2015-05-26 29 views
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; 
    }); 
}; 

这是一个管理页面上。该函数调用工厂(承诺),工厂删除服务器上的帐户。然后该函数删除范围内的元素,以便删除的元素不再显示。

我的测试看起来像这样:

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 } ]. 
+0

而......你的问题是什么? – Aracthor

+0

第一个元素未被删除 - 测试失败。 我想知道为什么数组没有改变。 –

回答

0

尝试调用deleteAccount$scope.$digest()。这是必需的,因为测试没有像在浏览器中正常运行的方式那样具有摘要循环。

$scope.deleteAccount($scope.accounts[0]); 
$scope.$digest(); 
expect($scope.accounts).toEqual([{_id: 2}, {_id: 3}]); 
+0

感谢您的回复,但恐怕它不起作用。我也试图侦测函数和$ scope。$ apply(),但错误依然存在。 –

+0

也许你还需要移动'$ httpBackend.flush()'在'deleteAccount'后面运行flush# – yarons

+0

移动flush没有工作的账号是未定义的。但在deleteAccount工作后第二次调用flush。非常感谢你。 ''' ... $ httpBackend.when('DELETE','/api/accounts/1').respond(fakeResponse); $ httpBackend.flush(); $ scope.deleteAccount($ scope.accounts [0]); $ httpBackend.flush(); ... ''' –