[英]Using Jest within webpack 4 project throws 'Jest encountered an unexpected token' error
I am trying to include Jest in my current React app project to do some testing.我正在尝试将 Jest 包含在我当前的 React 应用程序项目中以进行一些测试。
This worked great for a simple javascript file, but when I try and reference a file which uses import it throws the error 'Jest encountered an unexpected token'这对于一个简单的 javascript 文件非常有用,但是当我尝试引用一个使用 import 的文件时,它会抛出错误“Jest 遇到了意外的令牌”
I've been looking through the following guide and found I didn't have a.bablerc file我一直在查看以下指南,发现我没有 .bablerc 文件
https://jestjs.io/docs/en/webpack https://jestjs.io/docs/en/webpack
So I added one with the following, as per the example, but this has had no affect when I run npm run test因此,根据示例,我添加了以下内容,但这在我运行 npm 运行测试时没有影响
// .babelrc
{
"presets": [["env", {"modules": false}]],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
My current package.json I have added the following as per the instructions on a different page.我当前的 package.json 我根据不同页面上的说明添加了以下内容。
"scripts": {
"test": "jest"
},
My webpack config.js file looks like this.我的 webpack config.js 文件看起来像这样。
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const bundleOutputDir = './wwwroot/dist';
const javascriptExclude = [];
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
const javascriptExclude = [
/(node_modules|bower_components)/,
path.resolve('./ClientApp/scripts/thirdParty')
];
// if dev build then exclude our js files from being transpiled to help speed up build time
if (isDevBuild) {
javascriptExclude.push(path.resolve('./ClientApp/scripts'));
}
return [
{
stats: { modules: false },
entry: { main: "./ClientApp/index.js" },
resolve: { extensions: [".js", ".jsx"] },
output: {
path: path.join(__dirname, bundleOutputDir),
filename: "[name].js",
publicPath: "dist/"
},
module: {
rules: [
{
test: /\.js$/,
exclude: javascriptExclude,
use: {
loader: "babel-loader",
options: {
presets: ["babel-preset-env", "react", 'stage-2'],
plugins: [
"react-hot-loader/babel",
"transform-class-properties"
],
compact: false
}
}
},
{
test: /\.css$/,
use: isDevBuild
? ["style-loader", "css-loader"]
: ExtractTextPlugin.extract({ use: "css-loader?minimize" })
},
{
test: /\.(jpe|gif|png|jpg|woff|woff2|eot|ttf|svg)(\?.*$|$)/, use: [
{
loader: 'url-loader',
options: {
limit: 25000,
publicPath: '/dist/'
},
},
]
}
]
},
plugins: [
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require("./wwwroot/dist/vendor-manifest.json")
})
].concat(
isDevBuild
? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: "[file].map", // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(
bundleOutputDir,
"[resourcePath]"
) // Point sourcemap entries to the original file locations on disk
})
]
: [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin("style.css"),
new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } })
]
)
}
];
};
My example file I want to import from:我要从中导入的示例文件:
MyTestFile.js MyTestFile.js
export const Sum = (a, b) => {
return a + b;
}
MyTestFile.test.js MyTestFile.test.js
import { Sum } from './MyTestFile'
test('Add 1 + 2 = 3', () => {
expect(Sum(1,2)).toEqual(3);
});
Can anyone help?任何人都可以帮忙吗?
I have managed to get it to work using snippets from this answer... thanks to @sdgluck for pointing this out我已经设法使用这个答案中的片段让它工作......感谢@sdgluck指出这一点
Jest not parsing es6: SyntaxError: Unexpected token import 开玩笑不解析 es6: SyntaxError: Unexpected token import
package.json package.json
"scripts": {
"test": "jest --config jest.config.js"
},
Added babel.config.js添加了 babel.config.js
// babel.config.js
module.exports = {
presets: [
'@babel/preset-env'
]
}
Added jest.config.js添加 jest.config.js
module.exports = {
verbose: true,
rootDir: '../',
transform: {
'^.+\\.js?$': 'babel-jest',
}
}
Then it all worked然后一切正常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.