Testing a service using $ httpBackend in AngularJS

I am new to AngularJS and run into some problems with unit testing. I have seen many examples of bullying calls to $ httpBackend, but when I do this it will not work unless I also enable $ rootScope. $ Apply ().

My service:

angular.module('myApp.services', ['ngResource'])
  .factory('TestingService', ['$resource', function($resource) {
    return $resource('/api/v1/values', {}, {
      getValues: {
        method: 'GET'
      }
    });
  }]);

My unit test:

describe('Testing services', function() {
  beforeEach(module('myApp.services'));

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

  describe('TestingService', function() {
    it('would be nice to get an explanation for this',
        inject(['$rootScope', '$httpBackend', 'TestingService', 
          function ($rootScope, $httpBackend, testingService) {

          $httpBackend.expectGET('/api/v1/values').respond(100);

          var result = testingService.getValues();
          //$rootScope.$apply();

          $httpBackend.flush();
          expect(result).toBe(100);
          alert(result);
      }])
    );
  });
});

When Karma runs a test like this, I get:

Error: No pending request to flush !
Error: Unsatisfied requests: GET /api/v1/values

And if I include $ rootScope. $ apply (); I will get this (and the warning, of course, also gives the $ promise):

Expected { $promise : { then : Function, catch : Function, finally : Function }, $resolved : true } to be 100.

Can someone explain why I need "$ rootScope. $ Apply ();" skip waiting for a get? And why is the answer a promise instead of the false answer I indicated?

+4
source share
1 answer

. , .

Angular 1.3.0-beta.2, angular -mocks. "$ root. $Apply();".

:

describe('Testing services', function() {
  beforeEach(function(){
    module('myApp.services');
    this.addMatchers({
      toEqualData: function(expected) {
        return angular.equals(this.actual, expected);
      }
    });
  });

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

  describe('TestingService', function() {
    it('should work',
        inject(['$rootScope', '$httpBackend', 'TestingService', 
          function ($rootScope, $httpBackend, testingService) {

          $httpBackend.expectGET('/api/v1/values').respond( { key: 'value' } );

          var result = testingService.getValues();

          $httpBackend.flush();
          expect(result).toEqualData( { key: 'value' } );
          alert(angular.toJson(result, true));
      }])
    );
  });
});
+2

Source: https://habr.com/ru/post/1533019/


All Articles