Reputation: 22939
I've got a test suite and in each test file I find myself commonly importing a bunch of modules
const chai = require('chai')
const sinon = require('sinon')
const expect = chai.expect
const should = chai.should()
const testData = require('../test/test-data')
Is there any way to bundle all those require
calls in one require
, without using a namespace?
E.g something like this:
require('../test/test-bundle')
console.log(chai) // ok
console.log(sinon) // ok
console.log(expect) // ok
console.log(should) // ok
console.log(testData) // ok
Upvotes: 2
Views: 65
Reputation: 19587
I can not say that my solution is very good, but it will allow you to reduce the number of duplicate code. You could define a new module (test-util.js) and require all needed modules there. After that, in each test, require only one module and use destructuring assignment syntax to avoid namespace.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
test-util.js:
module.exports = {
chai: require('chai'),
sinon: require('sinon'),
expect: require('chai').expect,
should: require('chai').should(),
testData: require('../test/test-data')
};
test.js
let { chai, sinon, expect, should, testData } = require('./test-util.js');
Upvotes: 2