Using underscores in services for testing AngularJS

I will go through step 5 in the Corner Course section and stumbled upon this snippet in the testing section:

describe('PhoneCat controllers', function() {

  describe('PhoneListCtrl', function(){
  var scope, ctrl, $httpBackend;

  // Load our app module definition before each test.
  beforeEach(module('phonecatApp'));

   // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
   // This allows us to inject a service but then attach it to a variable
  // with the same name as the service.
   beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
   $httpBackend = _$httpBackend_;
   $httpBackend.expectGET('phones/phones.json').
     respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);

    scope = $rootScope.$new();
    ctrl = $controller('PhoneListCtrl', {$scope: scope});
}));

I do not fully understand the purpose of underlining an injection $httpBackend. I see a comment and understand what the code does. I just don’t understand why we only do this with help $httpBackend.

There are two other services that we introduce directly with her that do not need to be entered in this way. How do we help ourselves by introducing it $httpBackendin a workaround, and then immediately assign it to a variable with the same name, could we just enter it directly?

+3
source share
2 answers

$httpBackend , beforeEach it.

:

describe('PhoneCat controllers', function() {
    var $httpBackend; // variable declaration

     beforeEach(inject(function(_$httpBackend_) {
       $httpBackend = _$httpBackend_; // assignment
     }));

     it('should do something', function(){
        // usage
        $httpBackend.expectGET('/myurl').respond(function(){
            // some behaviour
        });
        // some assertion
     });
});
+2

, angular $injector , $httpBackend $httpBackend . .

"" , , $httpBackend $httpBackend,

var $httpBackend;

beforeEach(inject(function(_$httpBackend_) {
    $httpBackend = _$httpBackend_;
}));
+1

All Articles