繁体   English   中英

Jest 不使用 fs/promises typescript

[英]Jest not working with fs/promises typescript

我正在尝试将 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'
  ]
}

原来 Jest 将'fs/promises'为文件系统中的文件夹,这是不正确的,因为这是来自 fs 模块的 API。 要解决此问题,只需添加

moduleNameMapper: {
  "fs/promises": "<rootDir>/node_modules/fs-extra/lib/fs"
}

jest.config.js告诉 Jest 到 map 模块'fs/promises'到文件<rootDir>/node_modules/fs-extra/lib/fs ,或者文件系统中定义 fs 模块的任何地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM