Umair Sarfraz Umair Sarfraz - 1 year ago 170
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download