2

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!

The_Dude
  • 397
  • 1
  • 3
  • 16

1 Answers1

3

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
    }
})
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Thank you. But what if the mock data is quite long and the test.js contains several http request tests with different mock data (let's assume that all of them are large-scaled like this: http://www.sitepoint.com/youtube-json-example/)? Should I transfer the mock in a seperate JSON file to not overfill the test file with thousands of mock data lines? – The_Dude May 04 '16 at 06:03
  • Yes. You could..or else ypu could maintain that data in separate JavaScript file.. – Pankaj Parkar May 04 '16 at 06:13