使用jest process.cwd()获取测试文件目录

时间:2017-08-19 04:33:44

标签: javascript testing jest

在我目前的代码中,我使用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`);
}

但我不太喜欢这种解决方案,因为这种方法是适应测试的。

那么有什么建议吗?感谢。

1 个答案:

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