How to make a globally accessible variable?

tmacarthur picture tmacarthur · Jul 31, 2014 · Viewed 17.4k times · Source

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.

Answer

GrayedFox picture GrayedFox · Jul 7, 2015

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.