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)?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With