首页 > 解决方案 > 如何在 JEST 的 CRA 应用程序中使用“moduleDirectories”制作绝对导入模块

问题描述

我为我的测试创建了一些实用程序。我想以这种方式导入我的实用程序

import CustomRender from 'my-local-utils'

该目录将是

-src
 - components
  - __tests__
-test
  -my-loca-utils.js

通常我会将测试包含在 moduleDirectories 中的jest.config.js中,因此它被解析为全局。我实际上已经看到了一些 StackOverflow 的答案,说使用 CRA 它应该只在 package.json -> jest中使用。但是,该对象似乎只支持覆盖字段。请参阅下面的消息:

Out of the box, Create React App only supports overriding these Jest options:

  • clearMocks
  • collectCoverageFrom
  • coveragePathIgnorePatterns
  • coverageReporters
  • coverageThreshold
  • displayName
  • extraGlobals
  • globalSetup
  • globalTeardown
  • moduleNameMapper
  • resetMocks
  • resetModules
  • restoreMocks
  • snapshotSerializers
  • transform
  • transformIgnorePatterns
  • watchPathIgnorePatterns.

These options in your package.json Jest configuration are not currently supported by Create React App:

  • moduleDirectories

If you wish to override other Jest options, you need to eject from the default setup. You can do so by running npm run eject but remember that this is a one-way operation. You may also file an issue with Create React App to discuss supporting more options out of the box.

标签: reactjsjestjscreate-react-appts-jest

解决方案


您可以通过在您的 中执行以下操作来实现此目的package.json

{
  "jest": {
    "moduleNameMapper" {
      "my-local-utils": "<rootDir>/test/my-loca-utils.js"
    }
  }
}

请注意,我在您的文件结构中保留了我认为是错字的内容。


推荐阅读