从量角器进入工厂 [英] Access to factory from protractor
问题描述
我的应用程序中有一个小工厂( myFactory ):
Hi I have small factory (myFactory) in my application:
.factory('myFactory', ['$q', function ($q) {
function myMethod() {
.....
}
return {
myMethod: myMethod
};
}]);
我想在量角器测试中访问 myFactory.myMethod(),因此在onPrepare()中,我正在使用
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();
});
对于 console.log('myFactory:',myFactory)我看到我得到了对象:
for console.log('myFactory: ', myFactory) I see I get object:
myFactory: {
myMethod: {}
}
然后 myFactory.myMethod(); 我看到错误:TypeError:对象不是函数
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?
推荐答案
我使用服务通过Protractor访问我的应用程序中的用户信息,我继续并尽可能地在接近您的代码的位置进行操作,我在上面的评论应该是您的解决方案.这是更长的解释:
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:
因此,我们有一个 Users
服务,它具有一个名为 getCurrent()
的函数,该函数将检索当前用户的信息.因此,我第一次尝试使用与您相似的代码:
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
});
这记录了 Users
对象,并包含了函数 getCurrent()
,但是当我尝试链接调用 service时遇到了与您相同的错误.getCurrent()
.
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()
.
DID对我有用的只是将 .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, john.doe@email.com 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
});
仅是次要的FYI,您还可以通过将字符串传递给 executeScript
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);
});
这篇关于从量角器进入工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!