我正在开发一个 NodeJS (v. 8.12.0, EcmaScript 6) 项目,其项目结构类似于:
project_root/
src/
utils/
protocol_messages/
helpers.js
tests/
unit/
utils/
protocol_messages/
helpers.js
我正在使用 Mocha 作为测试框架编写测试。
问题
在
helpers.js
在 tests/unit/utils/protocol_messages/
下,导入被测模块的正确方法是什么?详细说明:
我想避免相对路径:
require('../../../../../src/utils/protocol_messages/helpers')
.它可以工作,但很难看,如果项目结构发生变化,我也必须重写测试导入。
(我是 Javascript 新手,所以我可能做错了几件事。)
更新
this question 中提供的解决方案:
require.main.require
: 在对 this answer 的评论中, “如果代码包含单元测试(如 Mocha 测试),则此解决方案将不起作用”。 node_modules
在我的src/
NodeJS 项目的项目根目录似乎没有意义。 如果我对上述任何一点有误,请指出,因为我很茫然。在我看来,NodeJS 并没有提供本地方式来导入具有绝对路径的 CommonJS 模块。
最佳答案
您可以使用wavy npm 包。
This module lets you turn things like require('../../../../foo') into something like require('~/foo'). The way it works is that on postinstall it creates a symlink in app/node_modules/~ to point to app/
关于node.js - 为特定模块编写测试时如何使用绝对导入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478251/