import with jest error: Unexpected token import

我与影子孤独终老i 提交于 2020-12-10 10:37:31

问题


I've seen similar questions but still can't find a viable solution.

I'm trying to integrate Jest into a working project, which uses import/export default in hundreds of places. The following test does work for Jest using require:

const bar = require('../../flows/foo');

test('adds 1 + 2 to equal 3', () => {
  expect(bar.foobar(1, 2)).toBe(3);
});

when export is:

module.exports = { 
 foobar: foobar,
  fizz: fizz
}

The functions I'll want to be testing however are exported using:

export default {
  foobar: foobar,
  fizz: fizz
};

So when I try to update my test to import:

import foobar from '../../flows/foo';

With export:

export default {foobar: foobar};

I get the error

SyntaxError: Unexpected token import

回答1:


All it takes:

// run this command (or npm equivalent)
yarn add @babel/core @babel/preset-env

// add babel.config.js
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        }
      }
    ]
  ]
};

Jest automatically picks it up, no other configuration required.




回答2:


You have not set up a .babelrc file in your project, so transpiling is not happening. You need to transpile the ES6+ syntax (import, export, etc) into browser readable ES5.




回答3:


I ran into this and solved it this way thanks to this GitHub issue post:

If you're using babel to transpile your code then remember to use the transform-es2015-modules-commonjs plugin.

To use it, you'll need to:

  1. Install the plugin for BabelJS by entering this command in the CLI:

npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

  1. Add the plugin to your list of plugins in your babel config
plugins: [
  "transform-es2015-modules-commonjs"
]


来源:https://stackoverflow.com/questions/44553020/import-with-jest-error-unexpected-token-import

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!