javascript 如何制作一个全局可访问的变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25067391/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a globally accessible variable?
提问by tmacarthur
How can I make a globally accessible variable in nightwatch.js? I'm using a variable to store a customized url (dependent on which store is loaded in our online product), but I need it to be accessible across several javascript functions. It appears the value of it resets after each function ends, despite it being declared outside of the function at the head of the file.
如何在 nightwatch.js 中创建一个全局可访问的变量?我正在使用一个变量来存储自定义 url(取决于我们的在线产品中加载的商店),但我需要它可以通过多个 javascript 函数访问。尽管它是在文件头的函数之外声明的,但它的值似乎在每个函数结束后都会重置。
回答by GrayedFox
It's been some time since you asked your question and support for what you requested might not have been (natively) available before. Now it is.
自从您提出问题以来已经有一段时间了,对您所请求的内容的支持可能以前(本地)不可用。现在它是。
In the developer guide two methods are provided for creating global variables accessible from any given test, depending on your needs. See herefor good reading.
在开发人员指南中,提供了两种方法来创建可从任何给定测试访问的全局变量,具体取决于您的需要。请参阅此处以获得良好的阅读。
Method 1: For truly global globals, that is, for all tests and all environments. Define an object, or pass a file, at the "globals_path" section of your nightwatch.json file, i.e.
方法 1:对于真正的全局全局变量,即对于所有测试和所有环境。在 nightwatch.json 文件的“globals_path”部分定义一个对象或传递一个文件,即
"globals_path": "./lib/globals.js",
You will need to export the variables, however, so brushing up on Node is a good idea. Here is a basic globals.js file example:
但是,您将需要导出变量,因此复习 Node 是个好主意。这是一个基本的 globals.js 文件示例:
var userNames = {
basicAuth: 'chicken',
clientEmail: '[email protected]',
adminEmail: '[email protected]',
};
module.exports = {
userNames: userNames
}
This object/file will be used for allof your tests, no matter the environment, unless you specify a different file/object as seen in method 2 below.
该对象/文件将用于您的所有测试,无论环境如何,除非您指定不同的文件/对象,如下面的方法 2 所示。
To access the variables from your test suite, use the mandatory browser/client variable passed to every function (test), i.e:
要访问测试套件中的变量,请使用传递给每个函数(测试)的强制性浏览器/客户端变量,即:
'Account Log In': function accLogin(client) {
var user = client.globals.userNames.clientEmail;
client
.url(yourUrl)
.waitForElementVisible('yourUserNameField', 1000)
.setValue('yourUserNameField', user)
.end();
}
Method 2: For environment based globals, which change depending on the environment you specify. Define an object, or pass a file, at the "globals" section of your nightwatch.json file, nested under your required environment. I.e.
方法 2:对于基于环境的全局变量,根据您指定的环境而变化。在您的 nightwatch.json 文件的“globals”部分定义一个对象或传递一个文件,嵌套在您所需的环境下。IE
"test_settings" : {
"default" : {
"launch_url" : "http://localhost",
"selenium_port" : 4444,
"selenium_host" : "localhost",
"globals": {
"myGlobal" : "some_required_global"
}
}
}
Please note that at the time of writing, there seems to be a bug in nightwatch and thus passing a file using Method 2 does not work (at least in my environment). More info about said bug can be found here.
请注意,在撰写本文时,nightwatch 中似乎存在错误,因此使用方法 2 传递文件不起作用(至少在我的环境中)。可以在此处找到有关上述错误的更多信息。
回答by imiric
To expand on Tricote's answer, Nightwatch has built-in support for this. See the documentation.
为了扩展 Tricote 的答案,Nightwatch 对此提供了内置支持。请参阅文档。
You can either specify it in the nightwatch.json
file as "globals": {"myvar": "whatever"}
or in a globals.js
file that you reference within nightwatch.json
with "globals": "path/to/globals.js"
. In the latter case, globals.js
could have:
您可以在nightwatch.json
文件中将其指定为 as"globals": {"myvar": "whatever"}
或在globals.js
您nightwatch.json
使用"globals": "path/to/globals.js"
. 在后一种情况下,globals.js
可能有:
module.exports = {
myvar: 'whatever'
};
In either case, you can access the variable within your tests as Tricote mentioned:
在任何一种情况下,您都可以像 Tricote 提到的那样访问测试中的变量:
module.exports = {
"test": function(browser) {
console.log(browser.globals.myvar); // "whatever"
}
};
回答by QualiT
I'll probably get down-voted for this, but another option that I have been using successfully to store and retrieve objects and data is to do a file write as key value pairs to an existing file.
我可能会为此被否决,但我成功使用的另一个选项是将文件作为键值对写入现有文件,用于存储和检索对象和数据。
This allows me to, at the end of a test run, see any data that was randomly created. I create this file in my first test script using all of the data I will use to create the various accounts for the test. In this way, if I see a whole lot of failures, I can take a look at the file and see what data was used, then say, log in as that user and go to that location manually.
这使我能够在测试运行结束时查看随机创建的任何数据。我在我的第一个测试脚本中创建了这个文件,使用了我将用来创建测试的各种帐户的所有数据。这样,如果我看到很多失败,我可以查看文件并查看使用了哪些数据,然后说,以该用户身份登录并手动转到该位置。
In custom commands I have a file that exports the following function:
在自定义命令中,我有一个导出以下函数的文件:
saveToFile : function(path, filename, data) {
this.yfs = fs;
buffer = new Buffer(data);
console.log("Note: About to update the configuration with test data" )
fs.open(path, 'w', function(err, fd) {
if (err) {
throw 'error opening file: ' + err;
}
fs.write(fd, buffer, 0, buffer.length, null, function(err) {
if (err) throw 'error writing file: ' + err;
return fs.close(fd, function() {
console.log('File write: ' + path + ' has been updated.' );
})
});
})
},
In this file, 'data' is key value pairs like "username" : "[email protected]". As a result I can use that data in later scripts, if so desired.
在这个文件中,'data' 是键值对,如“用户名”:“[email protected]”。因此,如果需要,我可以在以后的脚本中使用该数据。
This being true, I'll be exploring GrayedFox's answer immediately.
这是真的,我将立即探索 GrayedFox 的答案。
回答by Tricote
Not sure it's the best way, but here is how I do it : you can define a variable in the browser.globals
and access it in your different tests
不确定这是最好的方法,但我是这样做的:您可以在 中定义一个变量browser.globals
并在不同的测试中访问它
For instance :
例如 :
module.exports = {
before: function(browser) {
console.log("Setting up...");
// initialize global variable state
browser.globals.state = {};
},
"first test": function(browser) {
var settings = browser.globals,
state = browser.globals.state;
state.my_shared_var = "something";
browser.
// ...
// use a shared variable
.setValue('input#id', state.my_shared_var)
// ...
// ...
// save something from the page in a variable
.getText("#result", function(result) {
state.my_shared_result = result.value;
})
// ...
},
"second test": function(browser) {
var settings = browser.globals,
state = browser.globals.state;
browser.
// ...
// use the variables
.url("http://example.com/" + state.my_shared_result + "/show")
.assert.containsText('body', state.my_shared_var)
// ...
}
}
回答by vodolaz095
generaly it is a bad practice, but you can assign it as field of window
class.
一般来说,这是一种不好的做法,但您可以将其分配为window
类字段。
window.someGlobalVar = 'http://example.org/'
and window object is accessible globally
并且 window 对象可以全局访问