通过 Postman 或 Karate 执行 HTTP 端点时如何使用 Istanbul 收集代码覆盖率

Cap*_*irk 6 code-coverage node.js express istanbul karate

我有一个 JS 项目,它提供了一组利用 Express 和典型的 Express/路由器模式的端点。

const express = require('express');
const router = new express.Router();

router.post('/', async (req, res, next) => { });
router.get('/:abc', async (req, res, next) => { });

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

npm start我可以成功启动用于调用的服务器node ./src/index.js并使端点可用https://localhost:8080

我还可以利用 Postman 等工具或 Karate 等自动化工具成功测试这些端点。

我遇到的问题是,当通过http://localhost:8080行使产品源 JS 时,我似乎无法使用 Istanbul 收集代码覆盖率。

我已经尝试npm start过其次是nyc --all src/**/*.js gradlew test. 后者是测试端点的自动化。这导致 0% 的覆盖率,我假设这是由于没有使用 npm start 运行 nyc 造成的。

接下来我尝试nyc --all src/**/*.js npm start并注意到一些覆盖范围,但这只是启动 Express 服务器的覆盖范围。

接下来,我尝试了nyc --all src/**/*.js npm start以下操作gradlew test,发现代码覆盖率结果与未运行端点测试时的结果相同。

接下来,我尝试将前两个命令放入异步运行的单个 JS 脚本(myscript.js)中,其中 Express 服务器在 gradle 测试开始运行并运行之前启动nyc --all src/**/*.js myscript.js。结果与我之前的试验相同,其中只有 npm start 收到了代码覆盖率。

接下来,我尝试了nyc --all src/**/*.js npm start以下操作nyc --all src/**/*.js -no-clean gradlew test,发现代码覆盖率结果与未运行端点测试时的结果相同。

接下来,我尝试了上述所有尝试,将它们包装到 package.json 脚本中并运行npm run <scriptName>以获得相同的确切行为。

最后我尝试了nyc instrument src instrumented/src --compact=false其中npm run start:coverage的 start:coverage 脚本调用已检测的 index.js at ,node ./instrumented/src/index.js然后gradlew test调用nyc report --reporter=lcov. 此尝试也未能从 gradlew 端点测试中产生任何额外的代码覆盖率。

在网上做了一些研究,我发现了这篇文章 How do I setup codecoverage on my Express based API?

并认为这看起来与我的问题非常相似。例如,伊斯坦布尔在通过执行端点执行代码时不知道如何覆盖代码。

我决定仍然发布这篇文章,因为上面的帖子有点旧了,想征求意见,看看是否有比 https://github.com/gotwarlost/istanbul-middleware更好的解决方案

编辑

添加更多关于我们如何启动 Express 服务器并在没有伊斯坦布尔的情况下运行自动化的更多细节。只是为了澄清我们正在使用的内容以及我们投资的自动化工具。(主要是空手道和 Java)

/*
  calls --> node -r dotenv/config src/index.js
*/
npm start

/*
  calls --> gradlew clean test
  this effectively calls a tool called Karate
  Karate's base url is pointed to: https://locahost:8080
  Karate tests execute endpoints on that base url
  This would be akin to using Postman however Karate has quite a bit of configuration options
  https://github.com/intuit/karate
*/
npm test

Run Code Online (Sandbox Code Playgroud)

Cap*_*irk 4

经过几个小时的调查,我们已经成功解决了这个问题。@balexandre 发布的先前项目已更新以说明如何执行此操作。

https://github.com/kirksl/karate-istanbul