如何为react和jest测试框架配置.babelrc



我从头开始创建了一个react应用程序(createapp.dev(,并使用包裹捆绑器进行捆绑。

我试着用https://testing-library.com/开玩笑,但我总是犯这个错误

src/components/App.test.js
● Test suite failed to run
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.
By default, if Jest sees a Babel config, it will use that
to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed,
you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

如何修复?这些是我的文件.babelrc

{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
],
["@babel/preset-react"]
],
"plugins": ["@babel/plugin-proposal-class-properties" ]
}

package.json

{
"main": "src/index.js",
"scripts": {
"test": "jest",
"start": "parcel public/index.html --host 127.0.0.1 --port 8080",
},
"dependencies": {
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"devDependencies": {
"@babel/core": "^7.8.7",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"@babel/preset-env": "^7.8.7",
"@babel/preset-react": "^7.8.3",
"@testing-library/react": "^10.0.1",
"babel-jest": "^25.1.0",
"jest": "^25.1.0",
"parcel": "^1.12.4",
"parcel-bundler": "^1.12.4",
"prettier": "^1.19.1"
}
}

我意识到安装@testing-library/reactjest是不够的,我添加了以下

@testing-library/dom
@testing-library/jest-dom
@testing-library/user-event
babel-jest 

我还把我的.babelrc改成了这个

{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "current"
}
}
],
["@babel/preset-react"]
],
"plugins": ["@babel/plugin-proposal-class-properties" ]
}

最新更新