jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.27k stars 6.46k forks source link

[React-Native]SyntaxError: Unexpected token import #3332

Closed kimjuny closed 7 years ago

kimjuny commented 7 years ago

It seems babel transform works in my testcase code, but es6 syntax in node_modules does not.

Error

img

environment

npm 4.5

MacOS X

jest config

{
  "preset": "react-native",
  "globals": {
    "__DEV__": true
  },
  "transform": {
    "^.+\\.js$": "babel-jest"
  }
}

babelrc

{
  "env": {
    "test": {
      "presets": ["react-native"],
      "plugins": [["import", { "libraryName": "antd-mobile" }]]
    },
    "development": {
      "presets": ["react-native"],
      "plugins": [["import", { "libraryName": "antd-mobile" }]]
    },
    "production": {
    }
  }
}

testcase

import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import Index from '../index.ios.js';

it('renders correctly', () => {
  const tree = renderer.create(
    <Index />
  );
});

package.json

{
  "private": true,
  "scripts": {
    "web": "roadhog server",
    "build-web": "cross-env NODE_ENV=production roadhog build",
    "start": "react-native start",
    "ios": "cross-env NODE_ENV=development node themes/theme.rn.config.js && react-native run-ios",
    "android": "cross-env NODE_ENV=development node theme/theme.rn.config.js && react-native run-android",
    "lint": "eslint --ext .js src test",
    "precommit": "npm run lint",
    "test": "cross-env NODE_ENV=test jest --config .jest.config.json --no-cache"
  },
  "engines": {
    "install-node": "6.9.2"
  },
  "theme": "./themes/theme.web.config.js",
  "dependencies": {
    "antd-mobile": "^1.0.8",
    "babel-runtime": "^6.9.2",
    "dva": "^1.2.1",
    "lodash": "^4.17.4",
    "moment": "^2.18.1",
    "rc-form": "^1.3.0",
    "react": "15.4.2",
    "react-dom": "15.4.2",
    "react-native": "0.42.3",
    "react-native-chart": "^1.0.8-beta",
    "react-native-gesture-password": "^0.2.0",
    "react-native-scrollable-tab-view": "^0.7.4",
    "react-native-smart-gesture-password": "^2.1.0",
    "react-navigation": "^1.0.0-beta.7",
    "recharts": "^0.21.2",
    "socket.io-client": "^1.7.3"
  },
  "devDependencies": {
    "babel-eslint": "^7.1.1",
    "babel-jest": "^19.0.0",
    "babel-plugin-dva-hmr": "^0.3.2",
    "babel-plugin-import": "^1.1.1",
    "babel-plugin-transform-runtime": "^6.9.0",
    "babel-preset-react-native": "^1.9.1",
    "cross-env": "^4.0.0",
    "eslint": "^3.12.2",
    "eslint-config-airbnb": "^13.0.0",
    "eslint-plugin-import": "^2.2.0",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.8.0",
    "expect": "^1.20.2",
    "husky": "^0.13.3",
    "jest": "^19.0.2",
    "less-vars-to-js": "^1.1.2",
    "postcss-pxtorem": "^4.0.0",
    "react-test-renderer": "15.4.2",
    "redbox-react": "^1.3.2",
    "roadhog": "^0.6.0-beta1"
  }
}

debug message

jest version = 19.0.2
test framework = jasmine2
config = {
  "automock": false,
  "bail": false,
  "browser": false,
  "cacheDirectory": "/var/folders/h3/bfmnzb_j3zg3pdffgps1w3vh0000gn/T/jest",
  "clearMocks": false,
  "coveragePathIgnorePatterns": [
    "/node_modules/"
  ],
  "coverageReporters": [
    "json",
    "text",
    "lcov",
    "clover"
  ],
  "expand": false,
  "globals": {
    "__DEV__": true
  },
  "haste": {
    "defaultPlatform": "ios",
    "platforms": [
      "android",
      "ios",
      "native"
    ],
    "providesModuleNodeModules": [
      "react-native"
    ]
  },
  "moduleDirectories": [
    "node_modules"
  ],
  "moduleFileExtensions": [
    "js",
    "json",
    "jsx",
    "node"
  ],
  "moduleNameMapper": [
    [
      "^[./a-zA-Z0-9$_-]+\\.(bmp|gif|jpg|jpeg|png|psd|svg|webp)$",
      "RelativeImageStub"
    ],
    [
      "^React$",
      "/Users/erickim/Documents/Develop/react/glfm/node_modules/react"
    ]
  ],
  "modulePathIgnorePatterns": [
    "/Users/erickim/Documents/Develop/react/glfm/node_modules/react-native/Libraries/react-native/",
    "/Users/erickim/Documents/Develop/react/glfm/node_modules/react-native/packager/"
  ],
  "noStackTrace": false,
  "notify": false,
  "preset": "react-native",
  "resetMocks": false,
  "resetModules": false,
  "roots": [
    "/Users/erickim/Documents/Develop/react/glfm"
  ],
  "snapshotSerializers": [],
  "testEnvironment": "/Users/erickim/Documents/Develop/react/glfm/node_modules/jest-environment-node/build/index.js",
  "testMatch": [
    "**/__tests__/**/*.js?(x)",
    "**/?(*.)(spec|test).js?(x)"
  ],
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "testRegex": "",
  "testResultsProcessor": null,
  "testURL": "about:blank",
  "timers": "real",
  "transformIgnorePatterns": [
    "node_modules/(?!(jest-)?react-native|react-clone-referenced-element)"
  ],
  "useStderr": false,
  "verbose": null,
  "watch": false,
  "setupFiles": [
    "/Users/erickim/Documents/Develop/react/glfm/node_modules/babel-polyfill/lib/index.js",
    "/Users/erickim/Documents/Develop/react/glfm/node_modules/react-native/jest/setup.js"
  ],
  "transform": [
    [
      "^.+\\.js$",
      "/Users/erickim/Documents/Develop/react/glfm/node_modules/babel-jest/build/index.js"
    ]
  ],
  "rootDir": "/Users/erickim/Documents/Develop/react/glfm",
  "name": "005c8bf9b4d78dfa0bb0e32c0c55b0fb",
  "testRunner": "/Users/erickim/Documents/Develop/react/glfm/node_modules/jest-jasmine2/build/index.js",
  "cache": false,
  "watchman": true
}
kimjuny commented 7 years ago

I figured it out..

Alxmerino commented 7 years ago

@kimjuny I'm having a similar error but running with Travis CI, your solution did not work for me, do you have any suggestions?

kimjuny commented 7 years ago

@Alxmerino you can see this post, I'm not sure my case matches yours.

ghost commented 7 years ago

Exact same issue, was React Navigation. @kimjuny's link solved it. Just added the following to my jest config in package.json

"transformIgnorePatterns": [
  "node_modules/(?!react-native|react-navigation)/"
]

I used ignite to create my app, so my complete jest config now looks like this.

"jest": {
  "testMatch": [
    "**/Tests/**/*.js",
    "**/?(*.)(spec|test).js?(x)"
  ],
  "testPathIgnorePatterns": [
    "/node_modules/",
    "Tests/Setup.js"
  ],
  "setupFiles": [
    "./Tests/Setup"
  ],
  "preset": "react-native",
  "transformIgnorePatterns": [
    "node_modules/(?!react-native|react-navigation)/"
  ]
},

The line of code my test was hitting was trying to access NavigationActions from React Navigation

rochapablo commented 7 years ago

It never came to a conclusion, it always have a new error. =/

    TypeError: Cannot read property 'propTypes' of undefined

      at Object.<anonymous> (node_modules/react-native-gifted-chat/src/GiftedAvatar.js:160:31)
      at Object.<anonymous> (node_modules/react-native-gifted-chat/src/Avatar.js:4:19)
      at Object.<anonymous> (node_modules/react-native-gifted-chat/src/GiftedChat.js:16:13)

Ran all test suites matching "__tests__/test.spec.js".
  console.error node_modules/fbjs/lib/warning.js:36
    Warning: PropTypes has been moved to a separate package. Accessing React.PropTypes is no longer supported and will be removed completely in React 16. Use the prop-types package on npm instead. (https://fb.me/migrating-from-react-proptypes)
  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "./__tests__/setup.js"
    ],
    "testRegex": "/__tests__/.*\\.spec\\.js$",
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|react-navigation)/"
    ]
  }
akhileshk commented 7 years ago

I am getting exact same error, my problem is that I am using react-navigator

import React from 'react'; ^^^^^^ SyntaxError: Unexpected token import at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:306:17) at Object.get StackNavigator [as StackNavigator] (node_modules/react-navigation/src/react-navigation.js:27:12) at Object.<anonymous> (app.js:55:62)

Then I added this line in package.json

"transformIgnorePatterns": [ "node_modules/(?!react-native|react-navigation)/" ]

Then I started getting this error

` FAIL tests/index.ios.js ● Test suite failed to run

Invariant Violation: Native module cannot be null.

  at invariant (node_modules/fbjs/lib/invariant.js:44:7)
  at Linking.NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:32:1)
  at new Linking (node_modules/react-native/Libraries/Linking/Linking.js:119:141)
  at Object.<anonymous> (node_modules/react-native/Libraries/Linking/Linking.js:192:16)
  at Object.get Linking [as Linking] (node_modules/react-native/Libraries/react-native/react-native-implementation.js:96:22)
  at Object.<anonymous> (node_modules/react-navigation/src/PlatformHelpers.native.js:11:53)

`

arild-jacobsen commented 6 years ago

I believe I just had the same issue with recyclerlistview and solved it by transformIgnorePatterns as per @kimjuny's link.

Worth noting: react-native contains a preset file (node_modules/react-native/jest-preset.json) which you are using if your jest config says "preset": "react-native". It sets a value for "transformIgnorePatterns" which (for rn 47.9 at least) ignores all folders in node_modules except any which start with "react-native", "jest-react-native" or "react-clone-referenced-element".

To not change jest's behavior in undesired ways, you should copy the line from the preset in your version of react native into your jest config and modify it to also not ignore the module you need transformed.

e.g. my react-native/jest-preset.json had "transformIgnorePatterns": [ "node_modules/(?!(jest-)?react-native|react-clone-referenced-element)" ] so in my jest config i put "transformIgnorePatterns": [ "node_modules/(?!(jest-)?react-native|react-clone-referenced-element|recyclerlistview)" ] (technically this would also mean a module called "recylerlistview-extended-version" or similar would be transformed, but I can live with that)

Note also, since this is a list of patterns to ignore, and any path which matches any of the ignore patterns is ignored, all the paths to transform in node_modules has to be in the same pattern. So despite "transformIgnorePatterns" being an array, you can't split up the pattern for node_modules to transform.

jeff1evesque commented 6 years ago

I have jest defined as a script (renamed test:jest as test, when testing the uncommitted version), in my package.json. However, when running npm run test, I get SyntaxError: Unexpected token import:

root@browserify:/var/machine-learning/src# npm run test

> reactjs@1.0.0 test /var/machine-learning/src
> jest --config /var/machine-learning/test/jest/jest.config.js

 FAIL  ../test/jest/__tests__/layout/analysis.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/layout/analysis.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/layout/page.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/layout/page.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/content/register.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/content/register.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

 FAIL  ../test/jest/__tests__/content/login.test.jsx
  ● Test suite failed to run

    /var/machine-learning/test/jest/__tests__/content/login.test.jsx:6
    import React from 'react';
    ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../src/node_modules/jest-runtime/build/script_transformer.js:316:17)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 4 failed, 4 total
Tests:       0 total
Snapshots:   0 total
Time:        3.782s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! reactjs@1.0.0 test: `jest --config /var/machine-learning/test/jest/jest.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the reactjs@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-05-08T01_50_42_754Z-debug.log

I also defined a corresponding jest.config.js:

module.exports = {
  'verbose': true,
  'collectCoverage': true,
  'coverageDirectory': '/var/machine-learning',
  'moduleDirectories': ['/var/machine-learning/src/node_modules'],
  'transformIgnorePatterns': [
    '/var/machine-learning/src/node_modules'
  ]
}

I'm seeing a lot of things about react-native, and transformIgnorePatterns. Luckily, and unluckily, I don't use that. What an elusive bug this is. Do I need to define .babelrc, or add a jest directive in my package.json. How does my jest script know about babel, if this is the case? I've tried to add a .babelrc, in the same directory containing my package.json, with no luck:

{
  "env": {
    "test": {
      "presets": ["env", "stage-2", "react"]
    }
  }
}

Note: if anyone wants to keep track of my original issue regarding the above problem.

pxue commented 6 years ago

Just incase anyone stumbles upon this in future, and is having trouble with withNavigation from React Navigation, the solution is just to add react-navigation to ignored pattern via:

    jest: {
      "transformIgnorePatterns": [
        "node_modules/(?!react-native|react-navigation)/"
      ]
    }

in your package.json

github-actions[bot] commented 3 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.