用create-react-app开玩笑-意外的令牌错误 [英] Jest with create-react-app - unexpected token errors
问题描述
我正在开发一个应用程序,该应用程序最近已从旧的Webpack版本转换为使用create-react-app
.大部分过渡都进行得很顺利,但是在先前的单元测试中,我遇到了一些重大问题.当我运行具有标准"test": "react-scripts test --env=jsdom"
的package.json测试脚本的npm test
时,它说我所有的快照测试都失败了.很好,这是可以预期的,因为已经进行了很多更改,并且需要更新测试.
I am working on an application that was recently converted from an old Webpack build to use create-react-app
. Most of the transition has went smoothly, but I'm running into some major issues with the previous unit tests. When I run npm test
which has the standard package.json test script of "test": "react-scripts test --env=jsdom"
, it says all my snapshot tests have failed. This is fine and expected since there have been a lot of changes, and the tests need to be updated.
但是,当我只运行jest
或jest --updateSnapshot
时,我的所有测试都立即失败,并显示SyntaxError: Unexpected token
错误,其中大多数与import
有关.这使我相信Jest没有使用Babel正确转换ES6语法.
However, when I just run jest
or jest --updateSnapshot
, all of my tests immediately fail with SyntaxError: Unexpected token
errors, most of which are related to import
. This leads me to believe that Jest isn't using Babel to transform the ES6 syntax correctly.
以前,我们使用.babelrc文件进行以下设置:
Previously, we used a .babelrc file with these settings:
{
"presets": ["env", "react", "stage-0", "flow"],
"plugins": ["transform-runtime", "add-module-exports", "transform-decorators-legacy"]
}
但是由于Babel已经包含在create-react-app
中,因此我删除了此文件以及对Babel的任何引用.我的package.json也没有为Jest本身设置任何特殊的脚本.
But since Babel is already included in create-react-app
I removed this file as well as any references to Babel. My package.json also does not have any special scripts set up for Jest itself.
我尝试重新添加一些以前使用的Babel软件包,但是在进一步阅读之后,除非我从create-react-app
弹出,否则这些软件包仍然无法工作.
I have tried adding some of the previously used Babel packages back in, but after further reading it seems those won't work anyway unless I eject from create-react-app
and that is not an option at this time.
什么会导致npm test
正常运行但jest
严重失败?
What would cause npm test
to run correctly but jest
to fail miserably?
推荐答案
事实证明这是通天塔问题.即使create-react-app
已预先配置,我们仍然必须添加自定义配置,因为我们的应用程序最初不是使用cra
构建的.我安装了一些新的dev依赖项:
It turns out it was a Babel issue. Even though create-react-app
comes pre-configured, we still had to add in custom configuration since our app wasn't initially built with cra
. I installed some new dev dependencies:
"babel-cli": "^6.26.0",
"babel-jest": "^22.4.1",
"babel-preset-react-app": "^3.1.1",
并更新了.babelrc
:
{
"presets": ["babel-preset-react-app"]
}
现在jest
和npm test
都可以正常工作.
And now both jest
and npm test
both work as they should.
这篇关于用create-react-app开玩笑-意外的令牌错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!