我在Windows 8.1上使用 create-react-app
创建了一个干净的应用程序,运行Jest时遇到了问题。安装后,运行命令npm run test
,我收到以下错误消息:
No tests found related to files changed since last commit.
但是,在相同目录下运行 jest --watchAll
(绕过react-scripts)却能正常执行。
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
Details:
SyntaxError: E:\demo\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文件中添加Babel devDependencies。现在它看起来像这样:
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.2.3",
"@babel/plugin-transform-runtime": "^7.2.0",
"@babel/preset-env": "^7.2.3",
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.0.0",
"@babel/runtime": "^7.2.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.6.0",
"babel-loader": "^8.0.5",
"babel-plugin-root-import": "^6.1.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react-optimize": "^1.0.1",
"jest-transform-stub": "^1.0.0"
}
我也将.babelrc文件添加为:
{
"presets": [
"@babel/react" ,
"@babel/env"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
无论我尝试哪种组合,都会出现不同的错误,这一定不对。看看网上的人,所有人都能直接使用create-react-app中的Jest命令。
最后尝试了所有这些依赖项,结果出现以下错误:
Test suite failed to run
E:\dev\demo\src\App.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
有什么想法吗?!我感到困惑。
npm test
运行测试时遇到问题,那么这可能是 XY 问题。解决方案可以参考 https://dev59.com/_1kS5IYBdhLWcg3wiXMj 或者尝试使用npm test a
命令。 - Estus Flasknpm test a
就是答案,而且它运行得很好。感谢 @estus。如果你愿意,可以将你的解决方案作为普通答案添加,这样我就可以将其标记为正确答案。 - Dimitris Damilos