I am working on a NodeJS (v. 8.12.0, EcmaScript 6) project, whose project structure is similar to:
project_root/
src/
utils/
protocol_messages/
helpers.js
tests/
unit/
utils/
protocol_messages/
helpers.js
I am writing tests using Mocha as a test framework.
Question
In the helpers.js
under tests/unit/utils/protocol_messages/
, what's the proper way of importing the module-under-test?
To elaborate:
I want to avoid the relative path in: require('../../../../../src/utils/protocol_messages/helpers')
.
It works, but it's ugly, and if the project structure changes, I would have to rewrite the test imports, as well.
(I am new to Javascript so I might be doing several things wrong.)
Update
Solutions provided in this question:
require.main.require
: in a comment to this answer, "This solution will not work if code covered with unit tests like Mocha test".- Extracting my utils to a node module doesn't make sense for me, since the code is very application specific.
- Having an extra
node_modules
under mysrc/
project root of a NodeJS project doesn't seem to make sense. - Using a Javascript transpiler when I am using only features available in NodeJS and writing CommonJS projects seems a bit of an overkill.
If I am mistaken on any of the above points, please point it out, as I am at a loss. It seems to me like NodeJS doesn't not provide a native way to import CommonJS modules with absolute paths.