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_;
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.
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.
AngularJS also provides the ngMock module, which provides mocking for your tests. This is used to inject and mock AngularJS services within unit tests.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With