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 · 33 comments

Comments

Projects
None yet
@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

This comment has been minimized.

Collaborator

thymikee commented Mar 24, 2017

Can you setup a repo with the case?

@max-mykhailenko

This comment has been minimized.

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

This comment has been minimized.

Collaborator

SimenB commented Apr 2, 2017

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

@max-mykhailenko

This comment has been minimized.

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

This comment has been minimized.

Collaborator

SimenB commented Apr 2, 2017

did you try calling it test and not testing?

@max-mykhailenko

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

DimitryDushkin commented Apr 5, 2017

@max-mykhailenko try NODE_ENV=testing jest.

@max-mykhailenko

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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"
      ]
    }
  }

@mathisonian mathisonian referenced this issue Sep 23, 2017

Closed

Regroup #175

@rochapablo

This comment has been minimized.

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

This comment has been minimized.

Member

yangshun commented Sep 26, 2017

@rochapablo Did you tag the wrong person?

@rochapablo

This comment has been minimized.

rochapablo commented Sep 26, 2017

@yangshun, my bad!

Thanks.

@tachang

This comment has been minimized.

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

This comment has been minimized.

ironshark-sascha commented Mar 9, 2018

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

TheMightyPenguin added a commit to TheMightyPenguin/react-series-challenge that referenced this issue Mar 15, 2018

Remove example test
Used solution from this git comment:
facebook/jest#3202 (comment)

TheMightyPenguin added a commit to TheMightyPenguin/react-series-challenge that referenced this issue Mar 15, 2018

Remove example test
Used solution from this git comment:
facebook/jest#3202 (comment)
@dbernar1

This comment has been minimized.

@Izhaki

This comment has been minimized.

Izhaki commented May 9, 2018

For those like me...

Mind untranspiled imports from node_modules

Quite a few libraries ship nowadays with the module property set in package.json pointing at the untranspiled (es6, typescript) version of the library. Some bundlers use these by default.

However, as the docs state:

Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use transformIgnorePatterns to whitelist such modules. You'll find a good example of this use case in React Native Guide.

And the solution given here:

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

(goes in jest.config.js or jest key in package.json)

Having included the above, meant neither ["env", { "modules": "commonjs" }] in .babelrc nor any transfrom override in jest was needed.

@phyllisstein

This comment has been minimized.

phyllisstein commented May 25, 2018

I'm in a boat similar to @Izhaki's, but I'm trying to import untranspiled sources from a Lerna-symlinked package and can't seem to get Babel to transform it:

 FAIL  spec/app/routes/app/app-spec.tsx
  ● Test suite failed to run

    /Users/daniel/Repos/Postlight/BS/bs/packages/flux/src/index.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as actions from './actions';
                                                                                                    ^

    SyntaxError: Unexpected token *

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:396:17)
      at Object.<anonymous> (../storage-image.tsx:1:1)

My Jest config looks like this:

module.exports = {
  collectCoverage: true,
  collectCoverageFrom: [
    '<rootDir>/src/**/*.ts',
    '<rootDir>/src/**/*.tsx',
    '!**/node_modules/**',
    '!**/vendor/**',
  ],
  coverageDirectory: 'coverage',
  coverageReporters: [
    'html',
    'json',
    'lcov',
    'text',
  ],
  moduleFileExtensions: [
    'js',
    'jsx',
    'ts',
    'tsx',
  ],
  moduleNameMapper: {
    '\\.svg$': '<rootDir>/spec/mocks/react-svg.js',
  },
  modulePaths: [
    '<rootDir>/src/',
  ],
  setupTestFrameworkScriptFile: '<rootDir>/spec/setup.ts',
  testRegex: 'spec/.*-spec\\.tsx?$',
  transform: {
    '^.+\\.tsx?$': 'babel-jest',
  },
  transformIgnorePatterns: [
    'node_modules/(?!(@bs))',
  ],
}

The bizarre thing is that Babel must be reaching the file and doing something to it, because it's adding semicolons to the output in the error message. It's just not doing a complete transpilation. Has anyone run into something like this before?

@Robula

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

Robula commented Jun 1, 2018

Of course, that makes sense. 😄

@etoxin

This comment has been minimized.

etoxin commented Jul 23, 2018

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

@voxmatt

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

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

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

@sibelius

This comment has been minimized.

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment