Chen-Tai
Chen-Tai

Reputation: 3473

jest process.cwd() to get the test file directory

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.

Upvotes: 8

Views: 8917

Answers (2)

Oly Dungey
Oly Dungey

Reputation: 1677

__dirname does the trick nicely as module.parent is now deprecated as of Node v19.6.0 - https://nodejs.org/docs/latest/api/globals.html#__dirname

Upvotes: 2

WangJie
WangJie

Reputation: 334

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`);
}

Upvotes: 4

Related Questions