在我目前的代码中,我使用process.cwd()
获取当前工作目录,然后加载一些文件(如配置文件)。
下面我将展示我的代码的概念以及我如何测试它。
这是目录结构:
├── index.js
└── test
├── index.test.js
└── config.js
index.js
const readRootConfig = function() {
const dir = process.cwd();
console.log(dir); // show the working dir
const config = require(`${dir}/config.js`);
}
然后我用jest来测试这个文件。
index.test.js
import readRootConfig '../index';
it('test config', () => {
readRootConfig();
})
运行测试后,dir的console
为./
(实际输出为绝对路径,我只显示此演示中的相对路径)
但我希望dir的输出是./test
。
是否有任何配置让jest使用test file folder
作为process.cwd()
文件夹?
我认为其中一个解决方案是将dir path
作为参数传递,例如:
index.js
const readRootConfig = function(dir) {
console.log(dir); // show the working dir
const config = require(`${dir}/config.js`);
}
但我不太喜欢这种解决方案,因为这种方法是适应测试的。
那么有什么建议吗?感谢。
答案 0 :(得分:2)
也许您想制作一个可以知道所需文件的模块,您可以使用module.parent
。这是首先需要这个模块的模块。然后您可以使用path.dirname
来获取文件的目录。
所以index.js
应该是这样的
const path = require('path')
const readRootConfig = function() {
const dir = path.dirname(module.parent.filename)
console.log(dir); // show the working dir
const config = require(`${dir}/config.js`);
}