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 · 47 comments
Closed

Import not transpile with babel-jest #3202

brendonco opened this issue Mar 24, 2017 · 47 comments

Comments

@brendonco
Copy link

@brendonco brendonco commented Mar 24, 2017

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

@thymikee thymikee commented Mar 24, 2017

Can you setup a repo with the case?

@max-mykhailenko
Copy link

@max-mykhailenko max-mykhailenko commented Mar 27, 2017

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
Collaborator

@SimenB SimenB commented Apr 2, 2017

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

@max-mykhailenko
Copy link

@max-mykhailenko max-mykhailenko commented Apr 2, 2017

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
Collaborator

@SimenB SimenB commented Apr 2, 2017

did you try calling it test and not testing?

@max-mykhailenko
Copy link

@max-mykhailenko max-mykhailenko commented Apr 3, 2017

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

"scripts": {
  "test": "export NODE_ENV=testing && jest"
  ...
}
@DimitryDushkin
Copy link

@DimitryDushkin DimitryDushkin commented Apr 5, 2017

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

@DimitryDushkin DimitryDushkin commented Apr 5, 2017

@max-mykhailenko try NODE_ENV=testing jest.

@max-mykhailenko
Copy link

@max-mykhailenko max-mykhailenko commented Apr 6, 2017

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

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

@shahidjabbar shahidjabbar commented May 31, 2017

@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 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

@joseluisq joseluisq commented Jun 20, 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

👍

@kmiyashiro
Copy link

@kmiyashiro kmiyashiro commented Jun 28, 2017

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 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 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 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 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 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
Member

@yangshun yangshun commented Sep 26, 2017

@rochapablo Did you tag the wrong person?

@rochapablo
Copy link

@rochapablo rochapablo commented Sep 26, 2017

@yangshun, my bad!

Thanks.

@tachang
Copy link

@tachang 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

@ironshark-sascha ironshark-sascha commented Mar 9, 2018

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

@Robula
Copy link

@Robula Robula commented Jun 1, 2018

@phyllisstein I'm having the exact same problem, however I noticed that your config declares transform: { '^.+\\.tsx?$': 'babel-jest' }, you're pointing TS files to Babel; is that intended?

@phyllisstein
Copy link

@phyllisstein phyllisstein commented Jun 1, 2018

Ah, yeah---we're using the new Babel TypeScript parser in the v7 betas. I don't think that's what's causing it, though, since I can import the linked module through Webpack without any difficulty. (Though interestingly, the Babel CLI returns the same bad results...)

@Robula
Copy link

@Robula Robula commented Jun 1, 2018

Of course, that makes sense. 😄

@etoxin
Copy link

@etoxin etoxin commented Jul 23, 2018

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

@voxmatt
Copy link

@voxmatt 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

@phyllisstein phyllisstein commented Aug 7, 2018

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

@GeorgeTaveras1231 GeorgeTaveras1231 commented Oct 16, 2018

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
achenwei-chwy added a commit to achenwei-chwy/vuejs-storybook-storyshot-jest-webpack-boilerplate that referenced this issue Oct 26, 2018
@sibelius
Copy link

@sibelius sibelius commented Nov 11, 2018

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

@jackmahoney jackmahoney commented Feb 1, 2019

JS ecosystem makes me want to jump sometimes

@sibelius
Copy link

@sibelius sibelius commented Feb 1, 2019

check this for more info #7359

@simPod
Copy link

@simPod simPod commented Feb 1, 2019

@jackmahoney like out of window?

@JabbyPanda
Copy link

@JabbyPanda JabbyPanda commented Feb 13, 2019

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

@JabbyPanda JabbyPanda commented Feb 13, 2019

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

@holsted
Copy link

@holsted holsted commented Feb 13, 2019

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

@wjljan
Copy link

@wjljan wjljan commented Feb 20, 2019

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

@amazzalel-habib
Copy link

@amazzalel-habib amazzalel-habib commented Feb 20, 2019

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 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 tachang commented Jun 7, 2019

JS ecosystem makes me want to jump sometimes

Kubenetes says hold my beer.

@onyegood
Copy link

@onyegood 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

@raimonkh raimonkh commented Nov 15, 2019

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

@arvinsim arvinsim commented Dec 12, 2019

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 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet