从量角器访问窗口对象

从量角器访问窗口对象

本文介绍了从量角器访问窗口对象/浏览器范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用量角器运行测试,但似乎无法访问JS'window'对象。我甚至尝试在我的html文件中添加一个标签,其中包含类似

I'm running tests with protractor, but it seems impossible to access the JS 'window' object. I even tried adding a tag in my html file that would contain something like

var a = window.location;

然后尝试期待(a)但我无法使其工作,我总是得到未定义的引用...

and then try expect(a) but I couldn't make it work, I always get undefined references...

如何处理以访问浏览器范围内的变量?

How should I process to access variables that are in the browser scope ?

推荐答案

假设您使用的是最新版本的Protractor,假设> = 1.1.0,希望> = 1.3.1

Assuming you are using a recent version of Protractor, let's say >= 1.1.0, hopefully >= 1.3.1

尝试访问浏览器直接来自Protractor的JS代码不起作用,因为Protractor在NodeJS中运行,每个浏览器端代码都是通过Selenium执行的。

Attempting to access Browser side JS code directly from Protractor won't work because Protractor runs in NodeJS and every Browser side code is executed through Selenium JsonWireProtocol.

没有进一步的细节,一个工作的例子:

Without further detail, a working example:

browser.get('https://angularjs.org/');

一线承诺,截至今日,解析为'1.3。 0-rc.3'

One-liner promise that, as of today, resolves to '1.3.0-rc.3'

browser.executeScript('return window.angular.version.full;');

您可以直接在预期声明中使用它,因为Protractor期望为您解决承诺:

You can use it directly in an expect statement given Protractor's expect resolves promises for you:

expect(browser.executeScript('return window.angular.version.full;')).
  toEqual('1.3.0-rc.3');

更长的示例传递函数而不是字符串加上没有期望为您解决承诺。即为了更多的控制和对结果做一些奇特的事情。

Longer example passing a function instead of a string plus without expect resolving the promise for you. i.e. for more control and for doing some fancy thing with the result.

browser.driver.executeScript(function() {
    return window.angular.version.full;
}).then(function(result) {
    console.log('NodeJS-side console log result: ' + result);
    //=> NodeJS-side console log result: 1.3.0-rc.3
});

这篇关于从量角器访问窗口对象/浏览器范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 22:29