If you want to use babel-preset-env as a replacement for babel-preset-es2015 (which is deprecated) with Jest, then you have to make sure that the "modules" property in your "env" configuration is set to "commonjs".
Here is an exemplary configuration:
.babelrc
{
"env": {
"test": {
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"presets": [
"jest",
"react",
[
"env",
{
"debug": false,
"modules": "commonjs",
"targets": {
"node": "current"
},
"useBuiltIns": true
}
]
]
}
}
}
You can see in env.test
, that the preset env
(which is the "babel-preset-env" configuration) has "modules" set to "commonjs". That's important, otherwise you will get "SyntaxError: Unexpected token import".
For completeness, here is a simple test:
ExampleButton.test.jsx
import ExampleButton from './ExampleButton';
import React from 'react';
import renderer from 'react-test-renderer';
test('Example Test', () => {
const component = renderer.create(<ExampleButton />);
const json = component.toJSON();
expect(json.type).toBe('button');
});
ExampleButton.jsx
import React from 'react';
class ExampleButton extends React.Component {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.text}
</button>
)
}
}
export default ExampleButton;
For my Babel setup, I have used the following dependencies:
"babel-core": "6.26.0",
"babel-jest": "21.2.0",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-preset-env": "1.6.1",
"babel-preset-react": "6.24.1",
"jest": "21.2.1",
"react-test-renderer": "16.1.1",
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…