coverage-summary.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. Copyright 2012-2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. 'use strict';
  6. const percent = require('./percent');
  7. const dataProperties = require('./data-properties');
  8. function blankSummary() {
  9. const empty = () => ({
  10. total: 0,
  11. covered: 0,
  12. skipped: 0,
  13. pct: 'Unknown'
  14. });
  15. return {
  16. lines: empty(),
  17. statements: empty(),
  18. functions: empty(),
  19. branches: empty()
  20. };
  21. }
  22. // asserts that a data object "looks like" a summary coverage object
  23. function assertValidSummary(obj) {
  24. const valid =
  25. obj && obj.lines && obj.statements && obj.functions && obj.branches;
  26. if (!valid) {
  27. throw new Error(
  28. 'Invalid summary coverage object, missing keys, found:' +
  29. Object.keys(obj).join(',')
  30. );
  31. }
  32. }
  33. /**
  34. * CoverageSummary provides a summary of code coverage . It exposes 4 properties,
  35. * `lines`, `statements`, `branches`, and `functions`. Each of these properties
  36. * is an object that has 4 keys `total`, `covered`, `skipped` and `pct`.
  37. * `pct` is a percentage number (0-100).
  38. */
  39. class CoverageSummary {
  40. /**
  41. * @constructor
  42. * @param {Object|CoverageSummary} [obj=undefined] an optional data object or
  43. * another coverage summary to initialize this object with.
  44. */
  45. constructor(obj) {
  46. if (!obj) {
  47. this.data = blankSummary();
  48. } else if (obj instanceof CoverageSummary) {
  49. this.data = obj.data;
  50. } else {
  51. this.data = obj;
  52. }
  53. assertValidSummary(this.data);
  54. }
  55. /**
  56. * merges a second summary coverage object into this one
  57. * @param {CoverageSummary} obj - another coverage summary object
  58. */
  59. merge(obj) {
  60. const keys = ['lines', 'statements', 'branches', 'functions'];
  61. keys.forEach(key => {
  62. this[key].total += obj[key].total;
  63. this[key].covered += obj[key].covered;
  64. this[key].skipped += obj[key].skipped;
  65. this[key].pct = percent(this[key].covered, this[key].total);
  66. });
  67. return this;
  68. }
  69. /**
  70. * returns a POJO that is JSON serializable. May be used to get the raw
  71. * summary object.
  72. */
  73. toJSON() {
  74. return this.data;
  75. }
  76. /**
  77. * return true if summary has no lines of code
  78. */
  79. isEmpty() {
  80. return this.lines.total === 0;
  81. }
  82. }
  83. dataProperties(CoverageSummary, [
  84. 'lines',
  85. 'statements',
  86. 'functions',
  87. 'branches'
  88. ]);
  89. module.exports = {
  90. CoverageSummary
  91. };