user2961388
user2961388

Reputation: 33

Access to factory from protractor

Hi I have small factory (myFactory) in my application:

.factory('myFactory', ['$q',  function ($q) {

      function myMethod() {
        .....
      }

      return {
        myMethod: myMethod
      };
}]);

I want to get access to myFactory.myMethod() in protractor test so in onPrepare() I'm using

browser.executeScript(function() {
    return angular.element(document).injector().get('myFactory'); 
}).then(function (myFactory) {
    console.log('myFactory: ', myFactory);
    myFactory.myMethod();
});

for console.log('myFactory: ', myFactory) I see I get object:

myFactory:  { 
    myMethod: {}
}

Then for myFactory.myMethod(); I see error: TypeError: object is not a function

Anyone know how I can get access to factory from protractor to be able to execute method?

Upvotes: 1

Views: 191

Answers (1)

Gunderson
Gunderson

Reputation: 3268

I use services to access user information in my app via Protractor, I went ahead and played around with this as close to your code as I could, my comment above should be your solution. Here's the longer explanation:

So we have a service Users, with a function called getCurrent() that will retrieve the information of the current user. So first time I tried code similar to yours:

browser.executeScript(function () {
    return angular.element(document.body).injector().get('Users');
}).then(function (service) {
    console.log(service); // logs object which has getCurrent() inside
    service.getCurrent(); // error, getCurrent() is not a function
});

This logged the Users object, and included the function getCurrent(), but I encountered the same error as you when I tried to chain the call service.getCurrent().

What DID work for me, was simply moving the .getCurrent() into the execute script. i.e.

browser.executeScript(function () {
    return angular.element(document.body).injector().get('Users').getCurrent();
}).then(function (service) {
    console.log(service); // logs John Doe, [email protected] etc.
});

So applying that to your case, the below code should work:

browser.executeScript(function() {
    return angular.element(document).injector().get('myFactory').myMethod(); 
}).then(function (myFactory) {
    console.log(myFactory); // this should be your token
});

And just a minor FYI, for what it's worth you also could have written this code by passing in a string to executeScript:

browser.executeScript('return angular.element(document).injector().get("myFactory").myMethod()').then(function (val) {
    console.log(val);
});

Upvotes: 1

Related Questions