如何运行覆盖单个文件的 Jest 测试

Mar*_*vic 46 typescript reactjs jestjs react-scripts

我只想获得我目前正在处理的一个文件的覆盖率报告。

拥有整个应用程序文件的完整覆盖表,然后搜索我需要的文件,有点让人不知所措。

我尝试的是对一个文件运行测试并添加--coverage. 但它显示了所有文件的覆盖范围:

包.json

...
"test": "react-scripts test",
...
Run Code Online (Sandbox Code Playgroud)

我的命令

npm test my-component.test --coverage

是否可以向此命令添加一个选项以仅显示my-component.tsx覆盖范围?

Mar*_*vic 72

解决方案是添加一个小选项--collectCoverageFrom来仅收集某个文件(即组件)。这是基于这篇文章

NPM 版本
npm test my-component.test -- --coverage --collectCoverageFrom=src/components/my-component/my-component.tsx
注意--前面多了一个--coverage.... 这需要通过,因为npm如果没有它,将不会考虑提供的以下选项。

纱线版本
yarn test my-component.test --coverage --collectCoverageFrom=src/components/my-component/my-component.tsx

这将仅显示 的覆盖表my-component.tsx

笔记

文件路径my-component.tsx需要相对于项目根目录且准确。它不能像我所做的那样是相对的my-component.test

  • 如果有人想添加多个文件,您可以使用: `--collectCoverageFrom='["packages/**/index.js"]' --coverage` 。原始参考:https://github.com/facebook/jest/issues/1932 (2认同)
  • 这对我有用: npm test -- [fileName] --coverage (2认同)