简体   繁体   中英

angularjs phonecat tutorial step 5

I am reading the angularjs phonecat tutorial. I am currently on the step 5 .

In the section "Test", I've found this piece of code:

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 in order to avoid a name conflict.
  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 can't understand the reason to create the $httpBackend var. Can you guys explain me?

Thanks in advance.

$httpBackend needs to be accessible in all it test definitions later on. Thus it has to be in a parent closure of the it calls you'll write bellow.

beforeEach is the place where you do stuff that applies to all it calls so it is a sensible place to initialize $httpBackend .

Regarding the comment above it, if the parameter to inject would be named $httpBackend then inside that anonymous function you wouldn't have access to the "global" one (that's how closures work in JavaScript), so you would not be able to initialize it. Thus the people who wrote inject added this "magic" functionality regarding leading and trailing underscores, so that you can name it differently from the global variable that you need to initialize inside.

I'd recommend reading this to better understand closures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM