vendredi 18 août 2017

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.

Aucun commentaire:

Enregistrer un commentaire