What is the point of the underscores in Angular JS testing dependency injection

angularjs, karma-runner, testing

Solution

This one is more simple than it looks.

For convenience, we want to reference our services / scopes across our test suite as we are used to in our applications. So we need to save their reference at the outer function scope.

First we need to inject them so we try to do so without underscores like so:

var $httpBackend;

beforeEach(angular.mock.inject(function( $httpBackend ){

The problem is that the inner function scope variable `$httpBackend` shadows the outer function scope variable `$httpBackend`, so we cannot go up the scope chain to set our reference outside.

To fix it, we must have different names for the inner and the outer scope variables. The underscores are just a little help from the $injector to do it without pain.

Problem

I am currently working on a tutorial that integrates angular JS into a Rails app. Tests are setup as follows: ``` describe( 'Club functionality', function() { // mock Application to allow us to inject our own dependencies beforeEach(angular.mock.module('league')); // create the custom mocks on the root scope beforeEach(angular.mock.inject(function($rootScope, _$httpBackend_, $state){ //create an empty scope scope = $rootScope.$new(); // we're just declaring the httpBackend here, we're not setting up expectations or when's - they change on each test scope.httpBackend = _$httpBackend_; scope.$state = $state; })); afterEach(function() { scope.httpBackend.verifyNoOutstandingExpectation(); scope.httpBackend.verifyNoOutstandingRequest(); }); ... ``` After finishing that section of the tutorial and browsing some of the Angular docs it is still not clear to me why the underscores are used when including the $httpBackend dependency. Why is this mocked out like so? `scope.httpBackend = _$httpBackend_;`

Original source

Related problems