我正在尝试在我的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),
}),
],
config/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错误: ● 测试套件运行失败
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
我想要一个可用的测试运行器!我猜我的jest.config.js中的transform:babel-jest没有起作用...
create-react-app
创建的项目中遇到了同样的问题。由于配置是隐藏的,我不知道如何进行转译。我只知道node_modules
中的import
语句没有被转译(因此在 jest 中会抛出错误)。以上解决方案并没有起作用。有什么想法吗? - sookiecreate-react-app
中 eject,然后按照这个答案中的步骤进行操作。如果这样做不起作用,我建议你开一个新问题。 - sdgluck