Use the same variable in each test file

532 views Asked by At

For purpose of testing I am using multiple files. Each one represent one part of website for test.

In one of start test file I create variabile for name of new case, it looks like:

var moment = require('../../../../../node_modules/moment');

describe('Create new case', function() {

    var caseNumber = moment().format('YYYYMMDD-HHmmss-SS');

But somewhere at the end of all (in another test file) I would like to use this caseNumber again (exactly same as was used in first test, not generate new one).

Can anyone advise me how can I do it in protractor?

2

There are 2 answers

1
alecxe On BEST ANSWER

It doesn't sound quite right to have one test depending on an another test to define and export a variable. Set the global variable inside onPrepare() using global:

onPrepare: function() {
    global.caseNumber = moment().format('YYYYMMDD-HHmmss-SS');
},

Then, you'll have caseNumber as a global variable across all the tests.

1
Dziamid On

There's no need to use globals. You can make it more readable by creating your own module and requiring it:

//test/lib/homepage.js
var moment = require('moment');
module.exports = {
  caseNumber: moment().format('YYYYMMDD-HHmmss-SS'),

  getContent: function () {  //another example of reuse
    return element(by.css('body'));
  });
};

//test/homepage.spec.js
var page = require('./lib/homepage');

describe('Homepage', function() {
  it('should display correct date', function () {
    expect(page.getContent()).toContain(page.caseNumber);
  });
});