BonJon
BonJon

Reputation: 799

How do I mock the http requests in my case

I am having a weird issue regarding my unit test. In controller I have something like

testFactory.testFunction($scope.id)
       .then(function(returnData) {
           // do something with the return
       })

Factory file

test.testFunction = function(id) {
        return $http.get('/api/v.10/book/' + id + '/books');
};

unit test

var books = {data: {id: 333, name: 'my book'}};

beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, _testFactory_) {
        scope        = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        testFactory = _testFactory_;

        testCtrl = _$controller_('testCtrl', {
            $scope: scope
        });

        $httpBackend.whenGET('/api/v.10/book/333/books').respond(books);
    }));


 it('should check if test runs', function() {
         testFactory.testFunction(333).then(function(returnData){
                console.log(returnData)
         })
         $httpBackend.flush();
  })

For some reason, the console.log for the 'returnData' add the 'books' variable to an objects and add headers, status…etc to the response.

For example:

Object{data: Object{data: Object{id: ..., name: ...}}, 
             status: 200, headers: function (name) { ... }, 
             transformResponse: [...], 
             url: '/api/v.10/book/333/books', statusText: ''}

I am only expecting

{data: {id: 333, name: 'my book''}} as my response.

Can someone help me about the issue?

Thanks a lot!

Upvotes: 2

Views: 68

Answers (1)

Matthew Green
Matthew Green

Reputation: 10401

When using respond with a single parameter, it should be the data object you want returned to your web service, as shown under when in the docs. So you need to change your books variable to just {id: 333, name: 'my book'}.

Upvotes: 1

Related Questions