The_Dude
The_Dude

Reputation: 397

AngularJS - $httpBackend cannot read nested JSON property

I am trying to set up a http GET request expectation via jasmine but I'm getting following error:

TypeError: Cannot read property 'user' of undefined

The service function I want to test looks like:

function getData() {
    return $http.get('http://example.com/data')
        .then(function (response) {
            return response.data.example.user;
        });
}

A GET request to the URL "http://example.com/data" returns following data:

{
  "id": "1",
  "example": {
     "user": [
       {
          "name": "John",
          "wife": [
             {
                "name": "Jane",
                "age": "27"
             }
           ]
        }
    }
}

The corresponding test looks like this:

describe("Service: myService", function () {
    beforeEach(module("myApp"));

    var myService, $httpBackend;

    beforeEach(inject(function (_myService_, _$httpBackend_) {
        myService = _myService_;
        $httpBackend = _$httpBackend_;

        $httpBackend.whenGET("http://example.com/data").respond("some data");
    }));

    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it("should call the correct URL", function() {
        $httpBackend.expectGET("http://example.com/data");
        myService.getData();
        $httpBackend.flush();
    });

Somehow I am not able to test a http GET request as soon as the service function (that I want to test) returns a nested JSON property instead of the entire JSON.

Thanks in advance!

Upvotes: 2

Views: 162

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Data responded by API should be mock data in correct format, here getData is method is expecting in object format, so that could return user from it. like response.data.example.user

Code

$httpBackend.whenGET("http://example.com/data").respond({
  "id": "1",
  "example": {
     "user": [] //to keep you code working
    }
})

Upvotes: 3

Related Questions