【发布时间】:2019-11-15 23:34:11
【问题描述】:
我正在尝试运行使用 create-react-app 创建的反应应用程序。应用程序运行成功,但是当我尝试运行 JEST 时,它给了我以下错误。我已经查看并尝试了各种选项,但无法修复它。这是我的 package.json 和 jest.config.json
请就我可能做错的地方提出建议
谢谢 一个
错误
FAIL src/App.test.js
● 测试套件无法运行
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
Details:
SyntaxError: C:\Test\counter-app\src\App.test.js: Unexpected token (7:18)
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
> 7 | ReactDOM.render(<App />, div);
| ^
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
package.json
{
"name": "counter-app",
"version": "0.1.0",
"private": true,
"jest": {
"verbose": true,
"moduleDirectories": ["node_modules", "src"],
"transformIgnorePatterns": [
"node_modules/(?!(react-native|react-native-cookies)/)"
]
},
"dependencies": {
"bootstrap": "^4.3.1",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --env=jsdom",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
jest.config.js
const {defaults} = require('jest-config');
module.exports = {
"verbose": true,
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.(css|scss|less)$": "jest-css-modules",
".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
},
"globals": {
"NODE_ENV": "test"
},
moduleFileExtensions: [...defaults.moduleFileExtensions, 'js', 'jsx'],
"moduleDirectories": [
"node_modules",
"src/frontend",
"src/shared"
]
};
【问题讨论】:
-
也许可以试试 github 上的这个解决方案:github.com/facebook/jest/issues/6933#issuecomment-538317442
标签: reactjs jestjs babel-jest