gpt4 book ai didi

javascript - jest process.cwd() 获取测试文件目录

转载 作者:行者123 更新时间:2023-11-29 21:02:36 24 4
gpt4 key购买 nike

在我当前的代码中,我使用 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./(实际输出的是绝对路径,我在demo中只显示相对路径)

但是我希望dir的输出是./test.

是否有任何配置可以让 jest 使用 test 文件夹 作为 process.cwd() 文件夹?

我认为解决方案之一是将 dir path 作为参数传递,例如:

index.js

const readRootConfig = function(dir) {
console.log(dir); // show the working dir
const config = require(`${dir}/config.js`);
}

但是我不太喜欢这个方案,因为这个方法是为了适应测试。

有什么建议吗?谢谢。

最佳答案

也许你想制作一个模块,可以知道它需要什么文件,你可以使用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`);
}

关于javascript - jest process.cwd() 获取测试文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com