SyntaxError:使用Jest导入意外的令牌

问题描述 投票:3回答:1

我正在尝试使用redux-persist在我的react-native项目中设置一个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之前,我运行了完全相同的测试,它正在运行。

抛出的错误是:

●测试套件无法运行

/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)`
reactjs react-native jest redux-persist
1个回答
14
投票

该错误与es2015进口有关,但它是在jest结束。默认情况下,jest只转换项目代码和react-native代码。因此,添加的尚未发布的库将会因为开玩笑而错失。

(如在jest docs中提到的)

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

Solution在官方文档上提供似乎有点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)/)"
    ]
}

如果您从中导入redux-persist,请参阅PersistGate的附加说明

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

代替

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

(Qazxswpoi)

你会得到编译版本,但对于其他的libs,你仍然可以得到上面提到的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.