31

Is it possible to access angular within your protractor tests like you do in unit testing?

Use case is that I have a service that transforms text and I want to access that service to transform some data within the actual test script. I know there is the addMockModule method in protractor but I cannot figure out how to use it for this purpose.

Would appreciate any help!

wlingke
  • 4,699
  • 4
  • 36
  • 52

1 Answers1

37

There is a function called evaluate(). Find an element in the dom and then run the expression.

For example. If you want to count the number of todos in the http://angularjs.org/ website (under Add Some Control), do this:

Open the element explorer in protractor

./node_modules/protractor/bin/elementexplorer.js
browser.get('http://angularjs.org/')
element(by.model('todoText')).evaluate('todos.length').
  then(function(count) {
    console.log(count)
  });

It should give you a 2

You can also use executeAsyncScript

browser.executeAsyncScript(function(callback) {
  // Here we use document.body, but your app may live under a different
  // element.
  var service = angular.element(document.body)
      .injector()
      .get('myService');
  service.query({}, function(data) {
    callback(data);
  });
}).then(function (output) {
  console.log(output);
});

See an example: https://github.com/andresdominguez/protractor-meetup/blob/master/test/e2e/api-helper.js

Andres D
  • 8,910
  • 2
  • 26
  • 31
  • Got it, let me try out executeAsyncScript. The first one seems to be for more execution of simple things on a scope. – wlingke Dec 16 '13 at 20:36
  • 1
    the examples provided by the protractor-meetup on github are excellent, thanks so much for this. – FireDragon Oct 27 '14 at 12:00
  • 3
    Note that the 2nd variant actually **creates** a new injector. This can lead to errors like: `Unknown provider: $rootElementProvider` Use the ``angular.element([DOM element]).injector().get('myService');`` on a root DOM element (where the ng-app is set) to get the existing injector. – Vladius May 13 '15 at 13:18
  • We are no longer using this technique. I will update the answer. – Andres D May 17 '15 at 03:03
  • When I try to retrieve a value with .evaluate().then(), I'm getting an object with a lot of methods instead of the value – realisation Jan 31 '16 at 03:17
  • 2
    Is it good practice to access anything but the view in e2e tests? – Will Hardwick-Smith Jan 31 '16 at 23:03