mardi 26 mai 2015

Angularjs: Testing controller function, which changes $scope

I'm trying to test this controller function:

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

It is on a admin page. The function calls the factory (with promise) and the factory deletes the Account on the server. Then the function removes the element in the scope so that the deleted element isn't shown again.

My test looks like that:

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

Sadly the result is:

Expected [ { _id : 1 }, { _id : 2 }, { _id : 3 } ] to equal [ { _id : 2 }, { _id : 3 } ].

Aucun commentaire:

Enregistrer un commentaire