我有一个 JS 项目,它提供了一组利用 Express 和典型的 express/router 模式的端点。
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;
我可以用 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 脚本调用位于 node ./instrumented/src/index.js
的检测 index.js其次是 gradlew test
其次是 nyc report --reporter=lcov
.这种尝试也未能从 gradlew 端点测试中产生任何额外的代码覆盖率。
在网上做一些研究,我发现了这篇文章 How do I setup code coverage on my Express based API?
并认为这看起来与我的问题非常相似。例如, Istanbul 尔在通过执行端点执行代码时不知道如何覆盖代码。
我决定仍然发布这个,因为上面的帖子有点老了,想征求意见,看看是否有更好的解决方案 https://github.com/gotwarlost/istanbul-middleware
编辑
添加更多关于我们如何在没有 Istanbul 尔的情况下启动 Express 服务器和运行自动化的细节。只是为了阐明我们正在使用什么以及我们投资的自动化工具。(主要是 Karate 和 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
最佳答案
经过数小时的调查,我们设法解决了这个问题。 @balexandre 发布的先前项目已更新以说明如何执行此操作。
关于node.js - 通过 Postman 或 Karate 执行 HTTP 端点时如何使用 Istanbul 收集代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55922950/