Search code examples
angularjsangular-mock

How to make a REST API call in a controller Unit test?


I am trying to make a real call and Assign Scopes for testing Using passThrough Method but Throwing Error

Code Follows:-

describe('Controller: MainCtrl', function () {

          // load the controller's module
          beforeEach(module('w00App'));

          var scope, MainCtrl, $httpBackend;

          // Initialize the controller and a mock scope
          beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
                  $httpBackend = _$httpBackend_;
                  $httpBackend.expectGET('http://api.some.com/testdata').passThrough();


                  scope = $rootScope.$new();
                  MainCtrl = $controller('MainCtrl', {
                          $scope: scope
                  });
            })); it('should make a post to refresh the friends list and return    matching users', function(){

              var deferredResponse =  $httpBackend.expectGET('http://api.some.com/testdata').passThrough();
               console.log('response'+JSON.stringidy(deferredResponse));

              $httpBackend.flush();

             // expect(deferredResponse).toEqual(deferredResponse);
          }); });

Error :- TypeError: 'undefined' is not a function (near '... ').passThrough();...') .....

How can i call and Assign Scopes Like in Real controller ? pls Help.. it make my life Easy .


Solution

  • When testing a real controller and inside the controller you make some REST calls to the backed, it is best to mock those response calls, intercept the calls via $httpBackend object.

        jasmine.getJSONFixtures().fixturesPath = 'base/test/unit/authz/api_mock/';
        $httpBackend.when('POST', CONFIG.get('MAIN_URL_FOR_REST_SERVICES') + 'actions/search').respond(function() {
            return [200, window.getJSONFixture('actions.json')];
        });
    

    at least, this is how I proceed in testing the controllers.

    if you really really want to call the backed use:

    $http.get(YOUR_URL).success(function(data) {
       --- your test ---
    });
    

    and do not forget do inject the http service in the beforeEach method:

    beforeEach(inject(function(_$http_) {
       $http = _$http_;
    }));