Global variables aren't accessible in spec files protractor

548 views Asked by At

While automating angular 4 app, i need to declare some global variables i.e. myVar = 'John'. I tried declaring it in protractor.conf but its not working. I already have seen Protractor set global variables but these solutions don't work for me. Is there any solution to this? I am using protractor version 5.4.2.

exports.config = {
//..
params:{
myVar = 'John'
},

//..
}
I already have used this as well but its not working

onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
    //this global variable 
    global.myVar = 10000;
    
    browser.waitForAngularEnabled(false);
    browser.driver.manage().window().maximize();
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }

Thanks in Advance

3

There are 3 answers

1
DublinDev On BEST ANSWER

params is an object and therefore requires : to assign the value to myVar, not =.

exports.config = {
  params:{
    myVar:'John'
  },    
}

This is called in the following manner

console.log(browser.params.myVar)

The second method should work as it is. You just need to call it

onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
    //this global variable 
    global.myVar = 10000;

    browser.waitForAngularEnabled(false);
    browser.driver.manage().window().maximize();
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }

Called with

console.log(myVar);
0
Xotabu4 On

Also notice that when using 'global.blabla' or 'browser.params' with tests parallelization enabled (shardTestFiles: true) they will be read-only. This means if you will change these variables in one thread - other threads will be still having old value, since in protractor each test thread runs in separate nodejs process and they do not have shared memory.

1
Infern0 On

you are missing the tutorial:

params: {
   myVar: 500;
}

let a = browser.params.myVar;
console.log(a); // 500