In my current code, I use process.cwd()
to get the current working directory and then load some file (like config file).
Below I will show the concept of my code and how I test it.
This is the directory structure:
├── 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`);
}
And then I use jest to test this file.
index.test.js
import readRootConfig '../index';
it('test config', () => {
readRootConfig();
})
After run the test, console
of dir is ./
(real output is absolute path, I just show the relative path in this demo)
But what I hope the output of dir is ./test
.
Is there any config to make jest use the test file folder
to be the process.cwd()
folder?
I am thinking one of the solution is pass dir path
as a parameter, like:
index.js
const readRootConfig = function(dir) {
console.log(dir); // show the working dir
const config = require(`${dir}/config.js`);
}
But I am not pretty like this solution, cause this method is to adapt to the test.
So any suggestion? thanks.
Maybe you want to make a module that can know what file required it, you can use module.parent
. It is the module that first required this one. And then you can use path.dirname
to get the directory of the file.
So index.js
should be like this
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`);
}
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