Global variable that survives browser closed [wdio web driver io]

1.5k Views Asked by At

I have several suites and in each one some spec files.

What I noticed is that after wdio runs all tests in any spec file, it closes the browser and opens a fresh instance of the browser. Even the local storage is removed in this case.

So I have a hard time finding a place to define a variable that it's value persists throughout all tests.

I tried defining an array on top of my wdio.base.conf.js file.

let globalStuff = []

const config = { ...


beforeTest: function (test) {
      globalStuff.push(Math.random())
},

afterSession: function (config, capabilities, specs) {
    console.log(globalStuff)
    },
 }

Observation: The values of globalStuff are reseted each time and only contains x items (x is the number if it tests in a spec file)

Expectation: The values of globalStuff should be an aggregation of all pushed values.

1

There are 1 best solutions below

4
On

One easier way we are achieving this is using global object.

you can set something like global.platform = web in your config file and this should be accessible in all your tests. Similarly, you can set any number of unique properties on global object and they should be accessible in your tests.

Your snippet should be as below.

global.globalStuff = []

const config = { ...
  beforeTest: function(test) {
    globalStuff.push(Math.random())
  },

  afterSession: function(config, capabilities, specs) {
    console.log(globalStuff)
  },
}

Here is a sample project implementing this.