Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Protractor set global variables

I am trying to set a global variable on protractor to use in all describe blocks.

var glob = 'test';

describe('glob test', function () {
    it('should set glob', function () {
        browser.get('http://example.com/test');
        browser.executeScript(function () {
            window.glob = glob;
        });
    });    
});

But this returns me the following error:

Message:
[firefox #2]      UnknownError: glob is not defined

I also looked at this question: protractor angularJS global variables

so i tried to set the variable glob in conf.js in this way:

exports.config = {
  ...,
  onPrepare: function () {
      global.glob = 'test';
  }
};

Still, having the same error.

How can i add properly global variables in protractor tests?

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

It is possible to set globals from the Protractor config file with the help of params property:

exports.config = {
    // ...

    params: {
        glob: 'test'
    }

    // ...
};

And you can access it in the specs using browser.params.glob.

See the reference config file.

The params object will be passed directly to the Protractor instance, and can be accessed from your test as browser.params. It is an arbitrary object and can contain anything you may need in your test. This can be changed via the command line as:

protractor conf.js --params.glob 'other test'

Update:

From the docs for browser.executeScript:

If the script is provided as a function object, that function will be converted to a string for injection into the target window. Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments object.

So, JavaScript scope in this case does not work, you function that is passed to browser.executeScript won't have any closure variables from spec like browser. But you can pass these variables explicitly:

browser.executeScript(function (glob) {

    // use passed variables on the page
    console.log(glob);

}, browser.params.glob);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...