【问题标题】:Error when running jest on React-Native project在 React-Native 项目上运行 jest 时出错
【发布时间】:2019-02-20 15:26:07
【问题描述】:

在我的 react-native 项目上运行测试套件时,不断出现以下错误。

/.../node_modules/@expo/react-native-action-sheet/ActionSheet.ios.js:3
import React from 'react';
       ^^^^^

SyntaxError: Unexpected identifier

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (node_modules/@expo/react-native-action-sheet/index.js:1:45)

以下是使用的测试代码。这是一个简单的 Jest 快照测试

//ContactList Tests
import React from 'react';
import renderer from 'react-test-renderer';
import ContactList from '../components/ContactList';


//ContactList Snapshot
test('renders correctly', () => {
    const tree = renderer.create(<ContactList />).toJSON();
    expect(tree).toMatchSnapshot();
  });

我正在运行 react-native 版本 0.55.4 和 Jest 版本 23.6.0

【问题讨论】:

  • 你的 babel 配置是什么样的,它们位于什么文件中?
  • 这是来自 package.json 的 babel 配置
  • "devDependencies": { "babel-jest": "23.6.0", "babel-preset-react-native": "4.0.1", "jest": "^23.6.0 ", "react-test-renderer": "16.3.1" },
  • 我也希望获得您的.babelrcbabel.config.js 或类似的内容。
  • 对不起,这是我的 .babelrc 文件 { "presets": ["react-native"] }

标签: javascript react-native jestjs react-native-ios


【解决方案1】:

我以前看过这个

来自Jest docs

有时会发生(尤其是在 React Native 或 TypeScript 项目中)第 3 方模块以未转译的形式发布。由于默认情况下 node_modules 中的所有文件都没有进行转换,因此 Jest 将无法理解这些模块中的代码,从而导致语法错误。为了克服这个问题,您可以使用 transformIgnorePatterns 将此类模块列入白名单。你会在React Native Guide.中找到这个用例的一个很好的例子

在他们提到的 React Native Guide 中,您会从 package.json 中找到以下部分(这将嵌套在 jest 对象中):

"transformIgnorePatterns": [
  "node_modules/(?!(react-native|my-project|react-native-button)/)"
]

这是一个带有负前瞻的正则表达式,所以它的意思是:在node_modules 内,任何不是 紧跟react-nativemy-projectreact-native-button 的内容都是被忽略(不转换)。

或者为了简化这个双重否定,它将转换 node_modules 内的这三个包,而不是其他包。

在你的情况下,这个正则表达式可能看起来像这样:

"node_modules/(?!(react-native|@expo/react-native-action-sheet)/)"

这将允许react-native@expo/react-native-action-sheet 都被转译(我认为......你可能需要稍微尝试一下。可能有一些字符转义或其他一些需要白色的包 -列出)。

【讨论】:

  • 如果有帮助,这几乎就是我目前在 RN/expo 项目中使用的模式:"node_modules/(?!(react-native|static-container|expo|@expo|react-navigation))",我认为它会覆盖你。 (虽然你可能不需要react-navigation
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多