cowst cowst - 4 months ago 23
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");
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: [

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)?


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


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

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

and then import it to your other test files:


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