我有一个JS项目,提供了一组利用Express和典型Express / Router模式的端点。
const express = require('express');
const router = new express.Router();
router.post('/',async (req,res,next) => { });
router.get('/:abc',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)中,其中在gradle测试开始运行并运行nyc --all src/**/*.js myscript.js
之前启动Express服务器。得出的结果与我以前的试验相同,在该试验中,只有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?
并认为这看起来与我的问题极为相似。例如,伊斯坦布尔通过执行端点来执行代码时,不知道如何覆盖代码。
我决定仍然发布此内容,因为以上发布内容已经过时,并且想征求意见,看看是否有比此更好的解决方案 https://github.com/gotwarlost/istanbul-middleware
编辑
添加更多有关今天如何在不使用Istanbul的情况下如何启动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