Search code examples
javascriptangularjsselenium-webdriverprotractorangularjs-e2e

Protractor persistent variables


I'm trying to set up something similar to the Environment / Global variables in Postman. Postman stores these variables in JSON and when you modify them within a test, they will be the changed to the new values permanently. For example:

postman.setEnvironmentVariable("variable1", parseInt(postman.getEnvironmentVariable) +1);

This function would increment the Environment Variable by 1 at the start of a request. In my real Postman tests I use a custom function to calculate a valid EAN13 barcode based on the previously used barcode as they must be unique.

Is there anything like this that can be achieved in Protractor?


Solution

  • I've found an elegant solution to this. I import my params in a JSON object like below:

    global.DATA_PATH = './data/environment.json';
    global.fs = require(fs);
    exports.config = {
        ...
        params: {
            data = require(global.DATA_PATH)
        }
        ...
    };
    

    Then in my JSON object I'll define the data like so:

    {
        "variable1": "blah"
    }
    

    Now I can access my data through normal object dot notation in my code:

    this.modifyVariable1 = function(value) {
        params.data.variable1 = value;
    }
    

    Since this just modifies the variable params.data.variable1 in the parameters, I sync it with the file by using the nodejs module fs in afterAll:

    afterAll(function() {
        global.fs.writeFile(global.DATA_PATH, (JSON.stringify(params.data), null, 4), 'utf8);
    });
    

    This only needs to be run when the spec is done because changes to the params object persist through each it statement.

    Hope this helps others who wanted to try something similar!