gpt4 book ai didi

javascript - Protractor 设置全局变量

转载 作者:行者123 更新时间:2023-12-03 08:13:01 25 4
gpt4 key购买 nike

我正在尝试在 Protractor 上设置一个全局变量以在所有描述 block 中使用。

var glob = 'test';

describe('glob test', function () {
it('should set glob', function () {
browser.get('http://example.com/test');
browser.executeScript(function () {
window.glob = glob;
});
});
});

但这会给我返回以下错误:
Message:
[firefox #2] UnknownError: glob is not defined

我也看了这个问题: protractor angularJS global variables

所以我尝试以这种方式在 conf.js 中设置变量 glob:
exports.config = {
...,
onPrepare: function () {
global.glob = 'test';
}
};

尽管如此,还是有同样的错误。

如何在 Protractor 测试中正确添加全局变量?

最佳答案

可以借助 params 从 Protractor 配置文件中设置全局变量。属性(property):

exports.config = {
// ...

params: {
glob: 'test'
}

// ...
};

您可以使用 browser.params.glob 在规范中访问它.

reference config file .

The params object will be passed directly to the Protractor instance, and can be accessed from your test as browser.params. It is an arbitrary object and can contain anything you may need in your test. This can be changed via the command line as:


protractor conf.js --params.glob 'other test'
更新:

来自 docs for browser.executeScript :

If the script is provided as a function object, that function will be converted to a string for injection into the target window. Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments object.



因此,在这种情况下,JavaScript 范围不起作用,您传递给 browser.executeScript 的函数不会有任何来自规范的闭包变量,如 browser .但是您可以显式传递这些变量:
browser.executeScript(function (glob) {

// use passed variables on the page
console.log(glob);

}, browser.params.glob);

关于javascript - Protractor 设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31203398/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com