$ Injector Mocking Service

I have a situation where I want to add services inside the module, because I may not know that they are in advance. From a glance at the docs, it seems that the only way to do this (without a global scope) is through the Angular service $injector. However, it seems that this service is not mock-up, which makes sense, since the Angular method itself receives dependencies, which are still important even when testing.

Essentially, I am emulating a module NodeJS passport. I want to have something like a keychain where you add or remove an account at runtime. So far I have this:

angular.module('myModule').factory('accounts', function($injector) {
  return {
    add: function(name) {
      if(!$injector.has(name) {
        $log.warn('No Angular module with the name ' + name + ' exists. Aborting...');
        return false;
      }
      else {
        this.accounts[name] = $injector.get(name);
        return true;
      }
    },
    accounts: []
  };
});

However, when I try to make fun of a function $injectorin Jasmine, for example:

describe('accounts', {
  var $injector;
  var accounts;

  beforeEach(function() {
    $injector = {
      has: jasmine.createSpy(),
      get: jasmine.createSpy()
    };

    module(function($provide) {
      $provide.value('$injector', $injector);
    });

    module('ngMock');
    module('myModule');

    inject(function(_accounts_) {
      accounts = _accounts_;
    });
  });

  describe('get an account', function() {
    describe('that exists', function() {
      beforeEach(function() {
        $injector.has.and.returnValue(true);
      });

      it('should return true', function() {
        expect(accounts.add('testAccount')).toEqual(true);
      });
    });

    describe('that doesn't exist', function() {
      beforeEach(function() {
        $injector.has.and.returnValue(false);
      });

      it('should return true', function() {
        expect(accounts.add('testAccount')).toEqual(false);
      });
    });
  });
});

2- , accounts $injector, . , $injector.get $injector.has .

? , , , . ? , $injector?

, , , , ? , $injector , . inject, . , .

+4

All Articles