Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected token import with Jest

I'm trying to setup a jest snapshot test with redux-persist in my react-native project. I don't think its an es2015 imports problem as my test code looks something like this:

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()


})

I ran this exact same test before I added redux-persist and it was working.

Error thrown by jest:

● Test suite failed to run

/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)`
like image 848
Ahmad Avatar asked Dec 01 '22 14:12

Ahmad


1 Answers

The error was related to es2015 imports but It is on jest end. By default jest only transpiles project code and react-native code. So the added libs which aren't already transpilled would error out by jest.

(as mentioned on jest docs)

By default the jest-react-native preset only processes the project's own source files and react-native

Solution provided on the official docs seems a bit hacky but thats the only thing I found:

Add following in your package.json jest: { } section or in jest.config.js file.

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

where the bit redux-persist is the thing that solves the problem. If you have problem with other libs just add their names. My list looks something like this:

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

Additional Note just for redux-persist if you import PersistGate from

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

instead

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

(reference)

you'll get the compiled version but for other libs still you got to this the above mentioned solution.

like image 107
Ahmad Avatar answered Dec 03 '22 23:12

Ahmad