Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_;

like image 764
Davey Avatar asked Feb 03 '14 22:02

Davey


People also ask

What does underscore mean in AngularJS?

The underscores are a convenience trick we can use to inject a service under a different name so that we can locally assign a local variable of the same name as the service.

How to test directive AngularJS?

If a directive creates its own scope and you want to test against it, you can get access to that directive's scope by doing var directiveScope = myElement. children(). scope() - It will get the element's child (the directive itself), and get the scope for that.

Which component is used to inject and mock AngularJS service within the unit test?

AngularJS also provides the ngMock module, which provides mocking for your tests. This is used to inject and mock AngularJS services within unit tests.


1 Answers

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.

like image 85
Ilan Frumer Avatar answered Sep 30 '22 18:09

Ilan Frumer