The Vermilion Wizard
The Vermilion Wizard

Reputation: 5395

Jest Unexpected Identifier after import statement

I'm trying to use Jest to setup some tests for a React front end I'm writing for a Rails app. But when I try to run a simple test, Jest fails with an Unexpected identifier after my import statement.

blah.js

const fun = () => "fun";

export default fun;

blah.test.js

const x = 4;

import fun from './blah';

it('is fun', () => {
    fun();
});


Running yarn test fails with

import fun from './blah';
       ^^^

SyntaxError: Unexpected identifier

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

I threw in a const declaration before the import in the test file to see if it was failing to accept ES2015, but since it passes that I don't think there is a problem with babel.

I see a lot of questions about "unexpected token import" errors - this seems different because it is not complaining about the import token, but instead what comes after it.

Any suggestions on how I can get past this?


For reference, here are my configuration files:

.babelrc

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": "> 1%",
          "uglify": true
        },
        "useBuiltIns": true
      }
    ],
    "react"
  ],
  "plugins": [
    "syntax-dynamic-import",
    "transform-object-rest-spread",
    [
      "transform-class-properties",
      {
        "spec": true
      }
    ]
  ]
}

package.json

{
  "dependencies": {
    "@rails/webpacker": "3.5",
    "prop-types": "^15.6.2",
    "react": "^16.4.1",
    "react-dom": "^16.4.1",
    "react_ujs": "^2.4.4"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-jest": "^23.4.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "jest": "^23.4.1",
    "webpack-dev-server": "2.11.2"
  },
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "roots": [
      "spec/javascript"
    ],
    "moduleDirectories": [
      "node_modules",
      "app/javascript/components"
    ]
  }
}

Upvotes: 3

Views: 3005

Answers (1)

The Vermilion Wizard
The Vermilion Wizard

Reputation: 5395

OK it looks like the problem was in my .babelrc file. Correct version is this:

babel.rc

{
  "presets": [ "env", "react" ]
}

Upvotes: 1

Related Questions