问题
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:
- Install the plugin for BabelJS by entering this command in the CLI:
npm install --save-dev babel-plugin-transform-es2015-modules-commonjs
- 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