语法错误:使用Jest时出现意外的令牌导入。

4

我正在尝试在我的React Native项目中使用redux-persist设置Jest快照测试。 我认为这不是es2015导入问题,因为我的测试代码看起来像这样:

import React from "react"


import "react-native"



// Note: test renderer must be required after react-native.


import renderer from "react-test-renderer"



import App from "../App"



it("renders correctly", () => {
const app = renderer.create(<App />).toJSON()
expect(app).toMatchSnapshot()


})

在添加了redux-persist之前,我进行了完全相同的测试,并且测试是成功的。

Jest报错信息:

● 测试套件运行失败

/Users/a_050313/Documents/dev/scheduling/node_modules/redux-persist/es/integration/react.js:9
import React, { PureComponent } from 'react'; // eslint-disable-line import/no-unresolved
^^^^^^

SyntaxError: Unexpected token import

  1 | import React, { Component } from "react"
  2 | import { Provider } from "react-redux"
> 3 | import { PersistGate } from "redux-persist/es/integration/react"
  4 | 
  5 | import "./__debug__/ReactotronConfig" // Run Reactron Tools config
  6 | 

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
  at Object.<anonymous> (App.js:3:13)
  at Object.<anonymous> (__tests__/App.js:7:10)`
1个回答

20

该错误与es2015导入有关,但它是在jest端发生的。默认情况下,jest仅转译项目代码和react-native代码。因此,添加的库如果尚未转换,则会由jest报错。

(如jest文档中所述)

默认情况下,jest-react-native预设仅处理项目自己的源文件和react-native。

官方文档提供的解决方案似乎有些hacky,但这是我找到的唯一东西:

请在您的package.json jest: { }部分或jest.config.js文件中添加以下内容。

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

其中redux-persist是解决这个问题的库。如果你遇到其他库的问题,只需添加它们的名称即可。我的列表看起来像这样:

"jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
        "node_modules/(?!(react-native|my-project|redux-persist|react-native-linear-gradient|react-native-vector-icons|react-navigation)/)"
    ]
}

如果您从以下文件导入 PersistGate:

import { PersistGate } from "redux-persist/lib/integration/react"

请注意,这是一个编译版。而对于其他库,您需要使用上述提到的解决方案。

(参考链接)


请检查以下问题: https://dev59.com/4Krka4cB1Zd3GeqPdGiK - Adnan Ali
另外一个简单的解决方案也可以参考:https://github.com/expo/sentry-expo/issues/12 - jfunk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接