cowst cowst - 3 months ago 17
Javascript Question

How to add global variables used by all tests in Javascript?

I could not find how to remove code duplication in Javascript (basically what I would achieve in Java with base classes).

The concrete example is (at least) the following code, which is common to all spec files (and potentially page objects, since I am testing with that pattern in protractor):

var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var expect = chai.expect;


Can I do something to have expect available everywhere?
I tried in the protractor configuration to load a file with that before the specs:

specs: [
'e2e/helpers/commonDefinitions.js',
'e2e/**/*.spec.js'
]


or use beforeLaunch or onPrepare (but want a function, not sure how to expose vars that way), but without success.

However, I would prefer a generic Javascript approach to this kind of code reuse.

Is there any good way to avoid repeating this kind of common code everywhere, especially in tests (mocha, karma, protractor)?

Answer

One approach is to place that code in a separate file:

assert-styles.js

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var should = chai.should;

module.exports = {
  expect: expect,
  should: should
};

and then import it to your other test files:

test1.js

var assertStyles = require('./assert-styles');
var expect = assertStyles.expect;
var should = assertStyles.should;