Accessing Angular’s $injector from within Protractor

Reading Time: 2 minutesHere’s an uber hacky tip that purists will complain about: you can actually access angular’s $injector from within your Protractor test if you’re determined to. But a little warning, this is a bit hacky.

Why would we even need the injector in the first place? Well, let’s say we want to dynamically generate some reports based on some configuration data in our Angular app. In this example, say I have defined a list of reports in my Angular app and I want to use that list to dynamically generate some tests.

Here’s how you can access Angular’s $injector in your Protractor test.

  1. Somewhere in your app, set Angular’s $injector on $window like so:
  .run(function($injector, $window) {
    $window.$injector = $injector;

This is icky because we’re creating $injector as a global and there are all sorts of caveats about when you’re able to use it. But we’re not going to worry about that now #YOLO.

  1. Create a file helpers/injector.js in your tests with the following:
// helpers/injector.js
module.exports = function() {
  this.get = function(moduleName) {
      return browser.executeAsyncScript(
        function(moduleName, callback) {
      }, moduleName);

What we’re doing here is using browser.executeAsyncScript and using window.$injector to get the module we need.

  1. require your injector helper in your test
// in my_protractor_spec.js
var Injector = require('./helpers/injector');
  1. Use your Injector

As we mentioned earlier, in this example, let’s say we have an angular value ReportsList somewhere in our application and we want to dynamically generate tests based on that data:

// in my angular code
.value('ReportsList', function() {
  return [
   {name: "Budget Report", 
     url: "http://myapp/reports/budget"},
   {name: "Expenses Report", 
     url: "http://myapp/reports/expenses"},
   // etc.
// in my_protractor_spec.js
it('should download all the reports', function() {
  var injector = new Injector();
  injector.get('ReportsList').then(function(ReportsList) {
    ReportsList.forEach(function(report) {
      console.log("Downloading: " +
      // page is a page object previously defined 

Learn Protractor in a few hours with our online course

Protractor is a one of the best ways to ensure your app is working correctly because you can write code that acts like a real user. But Protractor can also be confusing and difficult to work with when you're just starting out. We've put together an online course that will help you become a master at Protractor.

You'll save tons of time and frustration learning Protractor because we've worked out everything you need to know. Become a Protractor testing master today!