Accessing Angular’s $injector from within Protractor

Here’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:

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:

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

  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:

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!