Create-React-App:无法从 package.json 脚本触发代码覆盖率报告

Create-React-App: Can't trigger code coverage report from package.json script

我在 create-react-app. Link to repo here;

package.jsonpackage.json 中的脚本中遇到了一些困难 运行

package.json

{
  "name": "React Kitchen Sink",
   ...
  "dependencies": {
    ...
    "react": "^16.14.0",
    "react-dom": "^16.14.0",
    "react-scripts": "^3.4.4"
  },
  "scripts": {
    "start": "react-scripts -r @cypress/instrument-cra start",
    "start:silent": "BROWSER=none yarn start",
    "start:server": "start-server-and-test start:silent http://localhost:3000",
    "build": "react-scripts build",
    "eject": "react-scripts eject",

    "jest:test": "react-scripts test --env=jest-environment-jsdom-sixteen",
    "jest:coverage": "react-scripts test --env=jest-environment-jsdom-sixteen --watchAll=false --coverage",
...
...

运行

yarn jest:test

以覆盖范围的监视模式开始测试,如果我按 a 然后我会收到一份所有测试都通过的报告

但如果我这样做

yarn jest:coverage

然后所有测试都失败了

错误看起来像这样:

 FAIL  src/components/Photo/index.test.js
  ● Console

    console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Uncaught [Error: Photo(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.]
          at reportException (/Users/norfeldt/Abtion/Playground/react-kitchen-sink/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:62:24)
          at innerInvokeEventListeners (/Users/norfeldt/Abtion/Playground/react-kitchen-sink/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:333:9)
          at invokeEventListeners

...

      The above error occurred in the <Photo> component:
          in Photo (at Photo/index.test.js:32)
      
      Consider adding an error boundary to your tree to customize error handling behavior.
      Visit <link> to learn more about error boundaries.

  ● has a test id

    Photo(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

...


试试这个脚本

react-scripts test --collectCoverage

这似乎是 create-react-app 版本 >3.4.1 中的一个已知问题,其中当 运行ning react-scripts test 带有标志 --watchAll=false--coverage同时。据报道 @facebook/create-react-app#8689

该错误后来通过将 CRA 中使用的 jest 版本更新为 PR @facebook/create-react-app#8362 中的 >25 版本得到修复。该修复包含在 CRA 的新主要版本 4.0.0 中。

因此,您应该将您的react-scripts包升级到版本>=4.0.0,然后按照this migration guide(看看是否有任何破坏影响您的更改)然后问题应该得到解决。

对于您的情况,我已经下载了您的存储库并完成了以下操作:

  1. 已删除 node_modules 个文件夹。
  2. 通过执行此命令 yarn add --exact react-scripts@4.0.0react-scripts 升级到版本 4.0.0(也可能是更高的 4.x 版本)。
  3. 运行 yarn install 再一次。
  4. 最后,再次尝试 yarn test:coverage,效果非常好:

如果其他人正在阅读本文并且出于某种原因升级到版本 4.0.0 不是一个选项,那么短期的简单解决方法是:

  • 删除标志 --watchAll=false 和 运行 像这样: react-scripts test --env=jest-environment-jsdom-sixteen --coverage
  • 或降级react-scripts至版本3.4.0。