Tim Lindsey Tim Lindsey - 2 years ago 53
Javascript Question

Use of underscores in services for AngularJS testing

I'm going through the AngularJS tutorial step 5, and came across 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.

// 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_;
respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);

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

I don't fully understand the purposes of the underscore when injecting
. I see the comment and understand what the code is doing. I just don't get why we are only doing this with

There are two other services we are injecting right along with it that don't need to be injected this way. How are we helping ourselves by injecting
in a roundabout manner then immediately assigning it to a variable of the same name, couldn't we just inject it directly?

Answer Source

Because that way you can declare $httpBackend in your describe, assign the injected service to it in a beforeEach and use it in your it blocks.


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

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

     it('should do something', function(){
        // usage
            // some behaviour
        // some assertion
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download