【发布时间】:2019-06-24 22:44:33
【问题描述】:
我正在尝试使用我的 webpack 项目设置 Jest。当我运行测试时,Jest 抱怨它无法读取 es6 代码。 Babel 似乎没有转换我的测试文件。
我尝试了在互联网上找到的各种解决方案,但我仍然感到困惑。也许有更多 Babel/Webpack 知识的人可以查看我的配置并帮助我。
相关 package.json 脚本:
{
"test": "jest --no-cache --config config/jest.config.js"
}
相关 package.json 部门:
"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.3.0",
"@babel/preset-env": "^7.3.1",
"@babel/preset-flow": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.0.0",
"babel-loader": "^8.0.5",
"babel-plugin-styled-components": "^1.10.0",
"jest": "^24.0.0",
"webpack": "^4.29.0",
"webpack-cli": "^3.2.1",
"webpack-dev-server": "^3.1.14"
config/webpack.config.js:
entry: './src/index.js',
mode: isProduction ? 'production' : 'development',
devtool: isProduction ? 'none' : 'inline-source-map',
bail: true,
devServer: {
contentBase: 'build',
compress: true,
port: 3000,
},
output: {
path: path.resolve(__dirname, 'build'),
filename: '[name].[chunkhash].js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-styled-components',
'@babel/plugin-proposal-class-properties',
],
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env),
}),
],
配置/jest.config.js
module.exports = {
verbose: true,
rootDir: '../',
setupFiles: ['./config/jest.setup.js'],
transform: {
'^.+\\.js?$': 'babel-jest',
},
config/jest.setup.js
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
开玩笑的错误: ● 测试套件无法运行
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
...
Details:
/<...projectpath>/config/jest.setup.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Enzyme from 'enzyme';
^^^^^^
SyntaxError: Unexpected token import
我想要一个可以工作的测试运行器!我猜我的变换:babel-jest 在我的 jest.config.js 中什么也没做......
【问题讨论】: