typescript - 找不到相对于目录的预设 "module:metro-react-native-babel-preset"

标签 typescript react-native jestjs

我正在尝试运行我的测试套件,但出现以下错误:

Couldn't find preset "module:metro-react-native-babel-preset" relative to directory "/Users/dan/Sites/X"

      at node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19
          at Array.map (<anonymous>)
      at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
      at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
      at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
      at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
      at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
      at File.initOptions (node_modules/ts-jest/dist/util/hacks.js:23:43)
      at new File (node_modules/babel-core/lib/transformation/file/index.js:135:24)
      at Pipeline.transform (node_modules/babel-core/lib/transformation/pipeline.js:46:16)

这是我在 package.json 中的 jest 配置:

"jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ],
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
      "\\.(ts|ts)x?$": "ts-jest"
    },
    "testRegex": "/src/.*.spec.(js|ts|tsx)?$",
    "globals": {
      "ts-jest": {
        "useBabelrc": true
      }
    }
  }

如果需要,这里是 babelrc 的内容

{
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": [
    [
      "module-resolver",
      {
        "alias": {
          "~": "./src"
        }
      }
    ]
  ]
}

最佳答案

This issue在撰写本文时仍然开放。

用户似乎对修复的结果不一,但这两个对我有用:

选项 1:将 .babelrc 更改为 .babelrc.js

只需将 .babelrc 重命名为 .babelrc.jsbabel.config.js

不要忘记将 module.exports = 添加到文件的开头。

这解决了我的 Jest 问题,但为我破坏了其他 eslint 插件。

选项 2:将转换添加到 Jest 配置

对于选项 2,我认为它通过在所有 javascript 文件上手动调用 react-native 预处理器来解决这个问题。

transform: { '^.+\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js' }

如果您没有单独的 Jest 配置文件,您可以将它添加到您的 package.json 中,例如...

{
  "jest": {
    "transform": { 
      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js" 
    }
  }
}

关于typescript - 找不到相对于目录的预设 "module:metro-react-native-babel-preset",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54107115/

相关文章:

javascript - react, typescript - 无状态和普通组件的类型

javascript - 命名空间方法不是函数

typescript - 使用vue-property-decorator时注册本地组件

ios - 无法打开,因为您没有查看权限 - React Native - Expo?

node.js - 用 Jest 测试 GraphQL 解析器

jestjs - 如何在 Cypress 中 stub 节点模块?

typescript - 从 Object => Object 映射 TypeScript 类型

javascript - React Native 超大图片定位

java - 在 React Native 的桥接 Java 方法中使用 Logback

typescript - 用 Jest 模拟 typescript 界面