Umair Sarfraz Umair Sarfraz - 3 months ago 26x
AngularJS Question

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

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


//Get data from URL
vm.getJson = function() {
var url = '',
count = 0;
$http.get(url).success(function(response) {
for (var i = 0; i <; i++) {[i].data);
if (count === {

vm.result = true;

}).error(function(err) {


The response I am getting is:
enter image description here


//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','').respond(200, dummyData);




}); });

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.


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','').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, = {name: 'Umair'} and that object has no child named children.

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