Jasmine angular unit test 'Cannot read 'property' of undefined

21,637

Solution 1

When your test is run, $httpBackend actually intercepts the $http.get call and assign dummyData to the response as you indicated in

$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);

This mocking behavior allows your unit tests to be completed quickly without being reliant on reddit being reachable from your test machine. So in your controller, response.data = {name: 'Umair'} and that object has no child named children.

To fix this, for dummyData, try mimicking the real data a bit more.

Solution 2

You're returning an object with a property name in your test and you're then trying to access the property data which is undefined.

You should simulate a real response object in your tests, e.g.:

var dummyData = {
  data: {
    children: [ 
    { data: 'foo'}
    ]
  }
};
Share:
21,637
Umair Sarfraz
Author by

Umair Sarfraz

Eat.Code.Ball.Code

Updated on March 24, 2020

Comments

  • Umair Sarfraz
    Umair Sarfraz about 4 years

    I have just started learning angular unit testing. However, this test on a function with http call fails. I have pin pointed the problem but however I am not being able to fix it. I know it's some simple issue

    Controller

    //Get data from URL
    vm.getJson = function() {
        var url = 'https://www.reddit.com/r/worldnews/new.json',
            count = 0;
        $http.get(url).success(function(response) {
            console.log(response);
            for (var i = 0; i < response.data.children.length; i++) {
                vm.data.push(response.data.children[i].data);
                count++;
                if (count === response.data.children.length) {
                    vm.numberOfPages();
                }
            }
    
            vm.result = true;
    
        }).error(function(err) {
            console.log(err);
        });
    
    };
    

    The response I am getting is: enter image description here

    Spec

     //Testing the getJson function
    describe('vm.getJson()', function() {
    
       it('It should return dummy Data as response and vm.result to be truthy', function() {
    
        var dummyData = {name: 'Umair'};
        $httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);
    
        MainCtrl.getJson(); 
    
        $httpBackend.flush();
    
        expect(MainCtrl.result).toBeTruthy();
    
    
    }); });
    

    I don't get any errors and the test passes if I remove the loop from the controller function. The error I am getting is:

    Cannot read 'Children' of undefined. From the image I have attached with the response data, children is the array.