【发布时间】:2021-10-26 00:48:40
【问题描述】:
我正在尝试将 jest 添加到我的 typescript 项目中进行测试,但是当我运行 jest 时,它一直给我错误
● Test suite failed to run
Cannot find module 'fs/promises' from 'src/path/to/file'
Require stack:
src/path/to/file
test/test.ts
> 3 | import fsp from 'fs/promises';
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)
at Object.<anonymous> (src/path/to/file.ts:3:1)
该程序本身运行良好,但每当我尝试对其运行 jest 时,它就会遇到这个问题。我尝试添加jest.mock('fs');,但没有帮助,添加jest.mock('fs/promises'); 在测试文件中会出现同样的错误。
我了解到某些版本的 Node 不支持 'fs/promises' 而需要 require('fs').promises,我已经尝试过但仍然无法正常工作(我使用的是 Node 版本 12)。
如何配置 jest 以加载 'fs/promises'?我在下面包含了我的jest.config.js 文件:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: [
'/node_modules/',
'/out/',
],
moduleDirectories: [
'.',
'node_modules'
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx'
]
}
【问题讨论】:
-
显示最小的、可重现的代码
-
将 ts-jest 添加到您的项目中。 npmjs.com/package/ts-jest
-
@slideshowp2 不幸的是,我无法提供项目本身,但我认为问题在于 jest 将“fs/promises”解释为文件系统中的文件夹,而实际上它是一个模块,所以我'必须以某种方式让开玩笑知道这件事,但我不知道在哪里/如何包含此注释
-
@StevenScott ts-jest 已添加到我的项目中,但这个问题仍然存在。
-
@slideshowp2 刚刚解决了这个问题。最后只是使用
moduleNameMapper添加了一张从'fs/promises'到<rootDir>/node_modules/fs-extra/lib/fs的地图
标签: node.js typescript webpack jestjs ts-jest