Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Import not transpile with babel-jest #3202

Closed
brendonco opened this issue Mar 24, 2017 · 48 comments
Closed

Import not transpile with babel-jest #3202

brendonco opened this issue Mar 24, 2017 · 48 comments

Comments

@brendonco
Copy link

execute yarn test throw an exception below.

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as actions from "../../src/actions/todoActions";
                                                                                             ^^^^^^
    SyntaxError: Unexpected token import
      
      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at process._tickCallback (internal/process/next_tick.js:109:7)

package.json

"jest": {
    "transform": {
      "^.+\\.js$": "babel-jest"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules",
      "bower_components"
    ]
  },

.babelrc

{
  "presets": [
    [
      "latest", {
        "es2015": {
          "modules": false
        }
      }
    ],
    "react",
    "stage-0"
  ],
  "plugins": [
    "react-hot-loader/babel",
    "syntax-dynamic-import",
    [
      "transform-runtime", {
        "helpers": false,
        "polyfill": false
      }
    ],
    "lodash"
  ],
  "env": {
    "test": {
      "plugins": ["dynamic-import-node"]
    }
  },
}

Any configuration I missed out?

@thymikee
Copy link
Collaborator

Can you setup a repo with the case?

@max-mykhailenko
Copy link

I have same error. My configs:

"dependencies": {
    ...
    "babel-core": "6.24.0",
    "babel-jest": "^19.0.0",
    "babel-plugin-transform-runtime": "6.23.0",
    "babel-polyfill": "6.23.0",
    "babel-preset-es2015": "6.24.0",
    "babel-preset-react": "6.23.0",
    "babel-preset-stage-1": "6.22.0",
    "enzyme": "2.8.0",
    "jest": "^19.0.2",
    "react-test-renderer": "15.4.2",
    ...
  },
  "jest": {
    "browser": true
  }

Jest debug output

jest "--debug"

jest version = 19.0.2
test framework = jasmine2
config = {
  "automock": false,
  "bail": false,
  "browser": true,
  "cacheDirectory": "/var/folders/kz/gn_dfwpd5w19y1dbt5gpmxl40000gn/T/jest",
  "clearMocks": false,
  "coveragePathIgnorePatterns": [
    "/node_modules/"
  ],
  "coverageReporters": [
    "json",
    "text",
    "lcov",
    "clover"
  ],
  "expand": false,
  "globals": {},
  "haste": {
    "providesModuleNodeModules": []
  },
  "moduleDirectories": [
    "node_modules"
  ],
  "moduleFileExtensions": [
    "js",
    "json",
    "jsx",
    "node"
  ],
  "moduleNameMapper": {},
  "modulePathIgnorePatterns": [],
  "noStackTrace": false,
  "notify": false,
  "preset": null,
  "resetMocks": false,
  "resetModules": false,
  "roots": [
    "/Users/max/Work/Projects/rgb-lab.net"
  ],
  "snapshotSerializers": [],
  "testEnvironment": "jest-environment-jsdom",
  "testMatch": [
    "**/__tests__/**/*.js?(x)",
    "**/?(*.)(spec|test).js?(x)"
  ],
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "testRegex": "",
  "testResultsProcessor": null,
  "testURL": "about:blank",
  "timers": "real",
  "transformIgnorePatterns": [
    "/node_modules/"
  ],
  "useStderr": false,
  "verbose": null,
  "watch": false,
  "rootDir": "/Users/max/Work/Projects/rgb-lab.net",
  "name": "1bc9e537b8b7dd004b3e65770d071eb7",
  "setupFiles": [
    "/Users/max/Work/Projects/rgb-lab.net/node_modules/babel-polyfill/lib/index.js"
  ],
  "testRunner": "/Users/max/Work/Projects/rgb-lab.net/node_modules/jest-jasmine2/build/index.js",
  "transform": [
    [
      "^.+\\.jsx?$",
      "/Users/max/Work/Projects/rgb-lab.net/node_modules/babel-jest/build/index.js"
    ]
  ],
  "cache": true,
  "watchman": true
}
 FAIL  source/js/configs/db.test.js
  ● Test suite failed to run

    /Users/max/Work/Projects/rgb-lab.net/source/js/configs/db.test.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export const users = {
                                                                                             ^^^^^^
    SyntaxError: Unexpected token export
      
      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at handle (node_modules/worker-farm/lib/child/index.js:41:8)
      at process.<anonymous> (node_modules/worker-farm/lib/child/index.js:47:3)
      at emitTwo (events.js:106:13)

 FAIL  source/js/components/__tests__/icon.test.js
  ● Test suite failed to run

    /Users/max/Work/components/__tests__/icon.test.js: Unexpected token (6:25)
        4 | 
        5 | test('Svg Icon markup test', () => {
      > 6 |   expect(renderer.create(<Icon name="user" />).toJSON()).toMatchSnapshot();
          |                          ^
        7 | });

@SimenB
Copy link
Member

SimenB commented Apr 2, 2017

@brendonco you have "modules": false, you have to activate that plugin for tests.

@max-mykhailenko
Copy link

I already add another environment to .babelrc for tests

{
  "ignore": [],
  "env": {
    "testing": {
      "presets": ["es2015", "stage-1", "react", "flow"],
      "plugins": ["lodash", "transform-runtime"]
    },
    "production": {
      "presets": [["es2015", { "modules": false }], "stage-1", "react", "flow"],
      "plugins": ["lodash", "transform-runtime"]
    },
    "development": {
      "presets": [["es2015", { "modules": false }], "stage-1", "react", "flow"],
      "plugins": ["lodash", "transform-runtime", "react-hot-loader/babel"]
    }
  }
}

@SimenB
Copy link
Member

SimenB commented Apr 2, 2017

did you try calling it test and not testing?

@max-mykhailenko
Copy link

@SimenB I also run all test with testing environment. packages.json looks like

"scripts": {
  "test": "export NODE_ENV=testing && jest"
  ...
}

@DimitryDushkin
Copy link

I found this error after recent babel update. Fixed by removing default preset and making separate presets for test, developent and production.

@DimitryDushkin
Copy link

@max-mykhailenko try NODE_ENV=testing jest.

@max-mykhailenko
Copy link

@DimitryDushkin I already do that and shown working .babelrc config for webpack@2 and jest

@cpojer cpojer closed this as completed Apr 11, 2017
@shahidjabbar
Copy link

@max-mykhailenko , what was your final solution? Getting a similar error with Jest. Repo at https://github.com/shahidjabbar/JestTest2.git

@max-mykhailenko
Copy link

max-mykhailenko commented May 31, 2017

@shahidjabbar Flow requires babel module "es2015", webpack with tree shaking requires ["es2015", { "modules": false }].

Full version .babelrc here #3202 (comment)

You should run flow with NODE_ENV=testing and webpack with development or production

@joseluisq
Copy link

@shahidjabbar Flow requires babel module "es2015", webpack with tree shaking requires ["es2015", { "modules": false }].

Full version .babelrc here #3202 (comment)

You should run flow with NODE_ENV=testing and webpack with development or production

👍

@kmiyashiro
Copy link

Can anyone confirm that the NODE_ENV should actually be testing and not test, which is the conventional test env value?

@ms88privat
Copy link

ms88privat commented Jun 30, 2017

Had the same problem. I had to remove my default presets and do it per environment basis like here #3202 (comment)

@kmiyashiro you can name it like you want (normally test). Just specify the name of the environment in the babelrc the same as the NODE_ENV variable.

@kmiyashiro
Copy link

kmiyashiro commented Jun 30, 2017

I have the correct settings and it works most of the time. Randomly, after a rebuild, I will get this error when I try to run jest. The only thing that fixes it is to delete the jest cache tmp dir, which you can find by running this in node:

console.log(require('os').tmpdir())

and then deleting jest* directories in that directory.

@bannier
Copy link

bannier commented Jul 6, 2017

my 2 cents if anyone has the same issue as me : coveragePathIgnorePatterns may also cause issues if you have modules using import in dependencies

@yogeshnikam
Copy link

yogeshnikam commented Jul 27, 2017

To resolve the error: Unexpected token import, you need to configure your .babelrc file with presets for test environment.

  "env": {
    "test": {
      "presets":[
        ["es2015", { "modules": false }],
        "react",
        "stage-0"
      ],
      "plugins": [
        "transform-es2015-modules-commonjs",
        "dynamic-import-node"
      ]
    }
  }

@rochapablo
Copy link

rochapablo commented Sep 26, 2017

@yogeshnikam, it didn't work. These are my files before changed:

package.json

  "jest": {
    "preset": "react-native",
    "testRegex": "/__tests__/.*\\.spec\\.js$",
    "setupFiles": [
      "./__tests__/setup.js"
    ],
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ]
  }

.babelrc

{
  "presets": [
    "react-native"
  ],
  "plugins": [
    ["module-resolver", {
      "cwd": "babelrc",
      "alias": {
        "~components": "./src/components",
        "~services": "./src/services"
      }
   }]
  ]
}
   /.../src/services/session/index.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as actions from './actions'
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runner/node_modules/jest-runtime/build/script_transformer.js:306:17)
      at Object.<anonymous> (__tests__/bootstrap.js:1:191)
      at Object.<anonymous> (__tests__/src/services/messages/index.spec.js:5:16)

It was all working, but I decided to start use ts files and everything stop working.

@yangshun
Copy link
Contributor

@rochapablo Did you tag the wrong person?

@rochapablo
Copy link

@yangshun, my bad!

Thanks.

@tachang
Copy link

tachang commented Feb 19, 2018

I put into my

package.json:

"test": "NODE_ENV=testing jest"

and .babelrc:

{
  "env": {
    "testing": {
      "presets":[
        ["env", { "modules": false }],
        "react",
      ],
      "plugins": [
        "transform-es2015-modules-commonjs",
      ]
    }
  }
}

@ironshark-sascha
Copy link

@tachang thx! this did the trick for me! :)

@Robula
Copy link

Robula commented Jun 1, 2018

Of course, that makes sense. 😄

@etoxin
Copy link

etoxin commented Jul 23, 2018

"Delightful JavaScript Testing" not when you run into this mess!

@voxmatt
Copy link

voxmatt commented Aug 6, 2018

@phyllisstein we're also using the new babel typescript parser, so I'm curious if you ever figured out a solution here

@phyllisstein
Copy link

Hey! Sorry I never updated this thread, I got pulled onto a different project at work and forgot about it. I've lost a little state about how I figured this out, but it turns out that you need to pass a babelrcRoots option to the babel-jest createTransformer function, then register that custom transformer in your Jest config.

Here's how we created the custom transformer:

const { join, resolve } = require('path')
const { createTransformer } = require('babel-jest')

const packagePath = resolve('../')
const packageGlob = join(packagePath, '*')

module.exports = createTransformer({
  babelrcRoots: packageGlob,
})

...and then here's the Jest config snippet:

module.exports = {
  transform: {
    '\\.tsx?$': '<rootDir>/spec/babel-transformer.js',
  },
}

This will force the transpiler to honor .babelrc files in packages' subdirectories. Good luck!

@GeorgeTaveras1231
Copy link
Contributor

Post babel 7 upgrade, I started to run into this issue. I was able to fix it by ensuring that babel-jest used the bridge version of babel-core.

Before fix:

yarn list babel-core

├─ babel-core@7.0.0-bridge.0
├─ babel-register@6.26.0
│  └─ babel-core@6.26.3
├─ jest-config@23.1.0
│  └─ babel-core@6.26.3
└─ jest-runtime@23.1.0
   └─ babel-core@6.26.3

Fix (package.json + yarn):

"resolutions": {
  "babel-core": "7.0.0-bridge.0"
}

After fix:

yarn list babel-core

warning Resolution field "babel-core@7.0.0-bridge.0" is incompatible with requested version "babel-core@^6.0.0"
warning Resolution field "babel-core@7.0.0-bridge.0" is incompatible with requested version "babel-core@^6.0.0"
warning Resolution field "babel-core@7.0.0-bridge.0" is incompatible with requested version "babel-core@^6.26.0"
warning Filtering by arguments is deprecated. Please use the pattern option instead.
└─ babel-core@7.0.0-bridge.0

adamchenwei added a commit to adamchenwei/vuejs-storybook-storyshot-jest-webpack-boilerplate that referenced this issue Oct 26, 2018
@sibelius
Copy link

I'm having the same issue for transpiling the setupFiles, I'm using babel.config.js in a monorepo with yarn workspaces, what is the right way of doing this config?

@jackmahoney
Copy link

JS ecosystem makes me want to jump sometimes

@sibelius
Copy link

sibelius commented Feb 1, 2019

check this for more info #7359

@simPod
Copy link

simPod commented Feb 1, 2019

@jackmahoney like out of window?

@JabbyPanda
Copy link

One of the possible solution is to update to Jest 24, that uses Babel 7 for its parts

With Jest 24 there is no conflicting issue with resolving modules between babel-core (Babel 6) and @babel/core (Babel 7) and "babel-core": "7.0.0-bridge.0" dependency is not required

@JabbyPanda
Copy link

Related issue #5525 that provides more information on how Jest relies on Babel 7 or Babel 6 for backward comparability

@holsted
Copy link

holsted commented Feb 13, 2019

@sibelius did you ever get that sorted? I have the same setup

@wjljan
Copy link

wjljan commented Feb 20, 2019

Have you tried this?
"env": { "test": { "plugins": [""transform-es2015-modules-commonjs"", "dynamic-import-node"] } }

@amazzalel-habib
Copy link

I'm having the same issue when I tried to test a monaco editor react component, it seems it doesn't find the package in node_modules when I run the test.

@wickkidd
Copy link

wickkidd commented Jun 7, 2019

FWIW, I've been beating my head against the wall for a day and a half with this issue. In my case, dropping back down to babel-jest v23.6.0 from v24.8.0 fixed it.

Also, Adam (@etoxin) your comment made my day. 😆

└─┬ @vue/cli-plugin-unit-jest@3.8.0
  ├── babel-jest@23.6.0
  └─┬ jest@23.6.0
    └─┬ jest-cli@23.6.0
      └─┬ jest-config@23.6.0
        └── babel-jest@23.6.0  deduped

@tachang
Copy link

tachang commented Jun 7, 2019

JS ecosystem makes me want to jump sometimes

Kubenetes says hold my beer.

@onyegood
Copy link

onyegood commented Sep 12, 2019

This is how I solved this problem.

Add to your dependencies list in your package.json file

"@babel/core": "^7.4.5",
"@babel/plugin-proposal-class-properties": "^7.4.4",
 "@babel/plugin-proposal-object-rest-spread": "^7.4.4",
"@babel/preset-env": "^7.4.5",
"@babel/preset-react": "^7.0.0",
 "babel-cli": "^6.26.0",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
"enzyme-to-json": "^3.4.0"

Your .babelrc in your root directory should look like this

{
  "presets": [
    "@babel/env", 
    "@babel/react"
  ],    
  "plugins": [
    "@babel/plugin-proposal-class-properties", 
    "@babel/plugin-proposal-object-rest-spread"
  ]
}

Create jest.config.json file in you root directory and the content should look like this

{
    "setupFiles": [
        "raf/polyfill",
        "<rootDir>/test/setupTests.js"
    ],
    "snapshotSerializers": [
        "enzyme-to-json/serializer"
    ]
}

Create a folder in your root directory called test and add setupTests.js file into it (test/setupTests.js). The content should look like this

import Enzyme from "enzyme";

import Adapter from "enzyme-adapter-react-16";

Enzyme.configure({ adapter: new Adapter() });

In package.json, in the script object let you test look like this

"test": "jest --config=jest.config.json --watch"

Delete your node_module folder and reinstall it again
npm install Or yarn install

Then do yarn test to run your test

I hope this help

@raimonkh
Copy link

I am currently seeing similar issues.

/<route>/node_modules/tipsi-stripe/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Stripe from './Stripe'
                                                                                                ^^^^^^

SyntaxError: Unexpected identifier



  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.<anonymous> (src/utils/stripe/tipsi_stripe.js:47:43)

we use

"@babel/core": "^7.3.4",
        "babel-core": "^7.0.0-bridge.0",
        "babel-eslint": "^10",
        "babel-jest": "^23",
        "jest-enzyme": "^4.0.1",
        "jest-junit": "^8.0.0",

I've done some of the changes suggested in this thread (like change the babel version to 3.6 or @phyllisstein babel-transformer without luck... i'm out of ideas...

@arvinsim
Copy link

I also get the same error

   /<route>/node_modules/antd/es/button/style/css.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import '../../style/index.css';
                                                                                                    ^^^^^^^^^^^^^^^^^^^^^^^

    SyntaxError: Unexpected string

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (node_modules/fxr-app-common/dist/fxr-app-common.cjs.development.js:7:1)

@yoannes
Copy link

yoannes commented Jun 30, 2020

this solved my problem:

rename .babelrc to babel.config.json...

original error:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import isObject from './isObject.js';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

@github-actions
Copy link

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.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests