Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to make a globally accessible variable?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 here for 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.

"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:

var userNames = {
  basicAuth: 'chicken',
  clientEmail: '[email protected]',
  adminEmail: '[email protected]',
};

module.exports = {
  userNames: userNames
}

This object/file will be used for all of your tests, no matter the environment, unless you specify a different file/object as seen in method 2 below.

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.

"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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...