首页 > 解决方案 > Jest 在用 jest 测试 react-native 时遇到了一个意外的令牌

问题描述

我想在我的 react-native 项目中使用 jest。我是开玩笑和反应原生的新手。目前低于错误

Details:

/Users/sachigrannan/SKO/Alpha4-1/node_modules/react-native-iphone-x-helper/index.js:1
import { Dimensions, Platform, StatusBar } from 'react-native';
       ^

SyntaxError: Unexpected token {

  at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
  at Object.<anonymous> (node_modules/react-navigation-stack/lib/commonjs/vendor/TransitionConfigs/CardStyleInterpolators.tsx:2:1)

我已经在 package.json 中设置了这个。请帮忙!

"jest": {
    "verbose": true,
    "preset": "react-native",
    "cacheDirectory": "./cache",
    "coveragePathIgnorePatterns": [
      "./app/utils/vendor"
    ],
    "coverageThreshold": {
      "global": {
        "statements": 80
      }
    },
    "transformIgnorePatterns": [
      "node_modules/(?!(react-native|my-project|react-native-button|nodejs-mobile-react-native|react-navigation)/)"
    ]
  }

标签: reactjsreact-nativetestingjestjs

解决方案


鉴于您的 transformIgnorePatterns 在引入 lib 之前工作,诀窍只是将“react-native-iphone-x-helper”添加到“transformIgnorePatterns”属性。

"node_modules/(?!(react-native|my-project|react-native-button|nodejs-mobile-react-native|react-navigation|react-native-iphone-x-helper)/)"

也就是说,您最好删除“transformIgnorePatterns”并让"preset": "react-native"配置完成其工作。

我在预设中遇到的唯一问题是当我在嵌套的 node_module 目录中有一个未编译的依赖项时,例如。

/path/to/myproject/node_modules/@react-navigation/bottom-tabs/node_modules/react-native-iphone-x-helper/index.js:1
    import { Dimensions, Platform, StatusBar } from 'react-native';
           ^

在这种情况下,问题是另一个模块使用了不同的版本,react-native-iphone-x-helper因此我必须更新该依赖项以便它们对齐。如果这不可行,你有纱线的分辨率字段


推荐阅读