From 6b9a476b0048e5c5cbb15bbdb77d5d40fe7d8278 Mon Sep 17 00:00:00 2001 From: Corey Farrell Date: Fri, 2 Aug 2019 08:51:37 -0400 Subject: [PATCH] fix: Drop unneeded coverage data from `nyc --all` (#456) Frequently users run `nyc --all` in a way that causes source files to be transpiled for actual testing but not transpiled for `--all`. This produces incompatible coverage data and inconsistantly wrong reporting. The work around here is to drop coverage produced by `--all` for any file where we have coverage produced by actual test runs. This ensures that we prefer code that was transpiled in the way which tests actually ran. Fixes #123, #224, #260, #322, #413 --- lib/file-coverage.js | 12 +++++++- test/file.test.js | 69 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/lib/file-coverage.js b/lib/file-coverage.js index 78907935..ed056a6f 100644 --- a/lib/file-coverage.js +++ b/lib/file-coverage.js @@ -157,6 +157,15 @@ class FileCoverage { * Note that the other object should have the same structure as this one (same file). */ merge(other) { + if (other.all === true) { + return; + } + + if (this.all === true) { + this.data = other.data; + return; + } + Object.entries(other.s).forEach(([k, v]) => { this.data.s[k] += v; }); @@ -246,7 +255,8 @@ dataProperties(FileCoverage, [ 'branchMap', 's', 'f', - 'b' + 'b', + 'all' ]); module.exports = { diff --git a/test/file.test.js b/test/file.test.js index 73f82196..167779e6 100644 --- a/test/file.test.js +++ b/test/file.test.js @@ -260,6 +260,75 @@ describe('base coverage', () => { assert.equal(c1.b[1][1], 2); }); + it('drops all data during merges', () => { + const loc = function(sl, sc, el, ec) { + return { + start: { line: sl, column: sc }, + end: { line: el, column: ec } + }; + }; + const template = new FileCoverage({ + path: '/path/to/file', + statementMap: { + 1: loc(1, 1, 1, 100), + 2: loc(2, 1, 2, 50), + 3: loc(2, 51, 2, 100), + 4: loc(2, 101, 3, 100) + }, + fnMap: { + 1: { + name: 'foobar', + line: 1, + loc: loc(1, 1, 1, 50) + } + }, + branchMap: { + 1: { + type: 'if', + line: 2, + locations: [loc(2, 1, 2, 20), loc(2, 50, 2, 100)] + } + }, + s: { + 1: 0, + 2: 0, + 3: 0, + 4: 0 + }, + f: { + 1: 0 + }, + b: { + 1: [0, 0] + } + }); + const clone = function(obj) { + return JSON.parse(JSON.stringify(obj)); + }; + const createCoverage = all => { + const data = clone(template); + if (all) { + data.all = true; + } else { + data.s[1] = 1; + data.f[1] = 1; + data.b[1][0] = 1; + } + + return new FileCoverage(data); + }; + + const expected = createCoverage().data; + // Get non-all data regardless of merge order + let cov = createCoverage(true); + cov.merge(createCoverage()); + assert.deepEqual(cov.data, expected); + + cov = createCoverage(); + cov.merge(createCoverage(true)); + assert.deepEqual(cov.data, expected); + }); + it('resets hits when requested', () => { const loc = function(sl, sc, el, ec) { return {