check-coverage.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const { relative } = require('path')
  2. const Report = require('../report')
  3. exports.command = 'check-coverage'
  4. exports.describe = 'check whether coverage is within thresholds provided'
  5. exports.builder = function (yargs) {
  6. yargs
  7. .example('$0 check-coverage --lines 95', "check whether the JSON in c8's output folder meets the thresholds provided")
  8. }
  9. exports.handler = function (argv) {
  10. // TODO: this is a workaround until yargs gets upgraded to v17, see https://github.com/bcoe/c8/pull/332#discussion_r721636191
  11. if (argv['100']) {
  12. argv.lines = 100
  13. argv.functions = 100
  14. argv.branches = 100
  15. argv.statements = 100
  16. }
  17. const report = Report({
  18. include: argv.include,
  19. exclude: argv.exclude,
  20. extension: argv.extension,
  21. reporter: Array.isArray(argv.reporter) ? argv.reporter : [argv.reporter],
  22. reportsDirectory: argv['reports-dir'],
  23. tempDirectory: argv.tempDirectory,
  24. watermarks: argv.watermarks,
  25. resolve: argv.resolve,
  26. omitRelative: argv.omitRelative,
  27. wrapperLength: argv.wrapperLength,
  28. all: argv.all
  29. })
  30. exports.checkCoverages(argv, report)
  31. }
  32. exports.checkCoverages = async function (argv, report) {
  33. const thresholds = {
  34. lines: argv.lines,
  35. functions: argv.functions,
  36. branches: argv.branches,
  37. statements: argv.statements
  38. }
  39. const map = await report.getCoverageMapFromAllCoverageFiles()
  40. if (argv.perFile) {
  41. map.files().forEach(file => {
  42. checkCoverage(map.fileCoverageFor(file).toSummary(), thresholds, file)
  43. })
  44. } else {
  45. checkCoverage(map.getCoverageSummary(), thresholds)
  46. }
  47. }
  48. function checkCoverage (summary, thresholds, file) {
  49. Object.keys(thresholds).forEach(key => {
  50. const coverage = summary[key].pct
  51. if (coverage < thresholds[key]) {
  52. process.exitCode = 1
  53. if (file) {
  54. console.error(
  55. 'ERROR: Coverage for ' + key + ' (' + coverage + '%) does not meet threshold (' + thresholds[key] + '%) for ' +
  56. relative('./', file).replace(/\\/g, '/') // standardize path for Windows.
  57. )
  58. } else {
  59. console.error('ERROR: Coverage for ' + key + ' (' + coverage + '%) does not meet global threshold (' + thresholds[key] + '%)')
  60. }
  61. }
  62. })
  63. }