Search code examples
angularjsjasmineangularjs-httpangular-mock

Angular unit test for adding up values


I'm new to angular unit test cases and I'm trying to write a unit test case for the following code that I have in my Angular controller. Data contains balance which is added up and assigned to $scope.Total

.success(function (data) {
$scope.Total = _.reduce(data, function(memo, value) {
                    return memo + value.Balance;
                }, 0);
});

My test case looks as follows

it('should return Total', function () {


                _http.whenGET('').respond([{
                    data: [
                    { Balance: 5 },{Balance:10}]
                }]);

                _controller();
                _http.flush();

                expect(_scope.Total).toBe(15);
            });

I keep getting the error Expected NaN to be 15.Error: Expected NaN to be 15.

Please let me know what I'm doing wrong here. Would be great if you can show me the correct code.

Thanks in advance.


Solution

  • I believe it is because of the incorrect data structure for the data stub in the httpBackend stubbing.

     _http.whenGET('').respond([{
                    data: [
                    { Balance: 5 },{Balance:10}]
      }]);
    

    Should be:

      _http.whenGET('').respond([{ Balance: 5 },{Balance:10}]);
    

    Looking at your implementation it looks like you are looking for array of objects with each object having balance property. Instead you are adding one more layer in the data structure.

    Plnkr

    A side note: You may want to abstract http calls to angular service and inject angular service in the controllers instead of directly using http. With that you achieve separation of concerns and single responsibility in your controller. Also you can easily create mocks for your service as well.