Accessing Angular inside Protractor Test

2019-01-09 00:27发布

问题:

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!

回答1:

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