Skip to content

Commit d3f53e3

Browse files
anthony-redFoxjohnjbarton
authored andcommittedOct 1, 2019
chore(all): Migrate to ES6 (#385)
* Convert InMemoryReport to the ES6 class * Use default params for reporters and coverageReporter * Remove lodash usages and dependencies * Replace all vars on const vs let in preprocessor
1 parent 9c8a222 commit d3f53e3

6 files changed

+87
-101
lines changed
 

‎lib/in-memory-report.js

+17-16
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,26 @@
1-
function InMemoryReport (opt) {
2-
this.opt = opt
3-
}
1+
class InMemoryReport {
2+
constructor (opt) {
3+
this.opt = opt
4+
}
45

5-
InMemoryReport.prototype.onStart = function (root, context) {
6-
this.data = {}
7-
}
6+
onStart () {
7+
this.data = {}
8+
}
89

9-
InMemoryReport.prototype.onDetail = function (node) {
10-
const fc = node.getFileCoverage()
11-
const key = fc.path
12-
this.data[key] = fc.toJSON()
13-
}
10+
onDetail (node) {
11+
const fc = node.getFileCoverage()
12+
const key = fc.path
13+
this.data[key] = fc.toJSON()
14+
}
1415

15-
InMemoryReport.prototype.onEnd = function () {
16-
if (!this.opt.emitter || !this.opt.emitter.emit) {
17-
console.error('Could not raise "coverage_complete" event, missing emitter because it was not supplied during initialization of the reporter')
18-
} else {
16+
onEnd () {
17+
if (!this.opt || !this.opt.emitter || !this.opt.emitter.emit) {
18+
console.error('Could not raise "coverage_complete" event, missing emitter because it was not supplied during initialization of the reporter')
19+
return
20+
}
1921
this.opt.emitter.emit('coverage_complete', this.opt.browser, this.data)
2022
}
2123
}
22-
2324
InMemoryReport.TYPE = 'in-memory'
2425

2526
module.exports = InMemoryReport

‎lib/preprocessor.js

+47-56
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,21 @@
66
// Dependencies
77
// ------------
88

9-
var { createInstrumenter } = require('istanbul-lib-instrument')
10-
var minimatch = require('minimatch')
11-
var path = require('path')
12-
var _ = require('lodash')
13-
var SourceMapConsumer = require('source-map').SourceMapConsumer
14-
var SourceMapGenerator = require('source-map').SourceMapGenerator
15-
var globalSourceMapStore = require('./source-map-store')
16-
var globalCoverageMap = require('./coverage-map')
9+
const { createInstrumenter } = require('istanbul-lib-instrument')
10+
const minimatch = require('minimatch')
11+
const path = require('path')
12+
const { SourceMapConsumer, SourceMapGenerator } = require('source-map')
13+
const globalSourceMapStore = require('./source-map-store')
14+
const globalCoverageMap = require('./coverage-map')
1715

1816
// Regexes
1917
// -------
2018

21-
var coverageObjRegex = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g
19+
const coverageObjRegex = /\{.*"path".*"fnMap".*"statementMap".*"branchMap".*\}/g
2220

2321
// Preprocessor creator function
24-
function createCoveragePreprocessor (logger, helper, basePath, reporters, coverageReporter) {
25-
var log = logger.create('preprocessor.coverage')
22+
function createCoveragePreprocessor (logger, basePath, reporters = [], coverageReporter = {}) {
23+
const log = logger.create('preprocessor.coverage')
2624

2725
// Options
2826
// -------
@@ -48,7 +46,7 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
4846
return new Obj.Instrumenter(opts)
4947
}
5048
}
51-
if (!_.isFunction(Obj)) {
49+
if (typeof Obj !== 'function') {
5250
// Object doesn't have old instrumenter variable and isn't a
5351
// constructor, so we can't use it to create an instrumenter
5452
return null
@@ -61,54 +59,49 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
6159
return Obj
6260
}
6361

64-
var instrumenterOverrides = {}
65-
var instrumenters = { istanbul: createInstrumenter }
66-
var includeAllSources = false
67-
var useJSExtensionForCoffeeScript = false
68-
69-
if (coverageReporter) {
70-
instrumenterOverrides = coverageReporter.instrumenter
71-
_.forEach(coverageReporter.instrumenters, function (instrumenter, literal) {
72-
var creatorFunction = getCreatorFunction(instrumenter)
73-
if (creatorFunction) {
74-
instrumenters[literal] = creatorFunction
75-
}
76-
})
77-
includeAllSources = coverageReporter.includeAllSources === true
78-
useJSExtensionForCoffeeScript = coverageReporter.useJSExtensionForCoffeeScript === true
79-
}
62+
const instrumenters = { istanbul: createInstrumenter }
63+
const instrumenterOverrides = coverageReporter.instrumenter || {}
64+
const { includeAllSources = false, useJSExtensionForCoffeeScript = false } = coverageReporter
65+
66+
Object.entries(coverageReporter.instrumenters || {}).forEach(([literal, instrumenter]) => {
67+
const creatorFunction = getCreatorFunction(instrumenter)
68+
if (creatorFunction) {
69+
instrumenters[literal] = creatorFunction
70+
}
71+
})
8072

81-
var sourceMapStore = globalSourceMapStore.get(basePath)
73+
const sourceMapStore = globalSourceMapStore.get(basePath)
8274

83-
var instrumentersOptions = _.reduce(instrumenters, function getInstrumenterOptions (memo, instrument, name) {
84-
memo[name] = {}
75+
const instrumentersOptions = Object.keys(instrumenters).reduce((memo, key) => {
76+
memo[key] = {}
8577

86-
if (coverageReporter && coverageReporter.instrumenterOptions) {
87-
memo[name] = coverageReporter.instrumenterOptions[name]
78+
if (coverageReporter.instrumenterOptions) {
79+
memo[key] = coverageReporter.instrumenterOptions[key]
8880
}
8981

9082
return memo
9183
}, {})
9284

9385
// if coverage reporter is not used, do not preprocess the files
94-
if (!_.includes(reporters, 'coverage')) {
86+
if (!reporters.includes('coverage')) {
9587
return function (content, _, done) {
9688
done(content)
9789
}
9890
}
9991

10092
// check instrumenter override requests
10193
function checkInstrumenters () {
102-
return _.reduce(instrumenterOverrides, function (acc, literal, pattern) {
103-
if (!_.includes(_.keys(instrumenters), String(literal))) {
94+
const keys = Object.keys(instrumenters)
95+
return Object.values(instrumenterOverrides).some(literal => {
96+
const notIncluded = !keys.includes(String(literal))
97+
if (notIncluded) {
10498
log.error('Unknown instrumenter: %s', literal)
105-
return false
10699
}
107-
return acc
108-
}, true)
100+
return notIncluded
101+
})
109102
}
110103

111-
if (!checkInstrumenters()) {
104+
if (checkInstrumenters()) {
112105
return function (content, _, done) {
113106
return done(1)
114107
}
@@ -117,20 +110,19 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
117110
return function (content, file, done) {
118111
log.debug('Processing "%s".', file.originalPath)
119112

120-
var jsPath = path.resolve(file.originalPath)
121-
// default instrumenters
122-
var instrumenterLiteral = 'istanbul'
123-
124-
_.forEach(instrumenterOverrides, function (literal, pattern) {
113+
const jsPath = path.resolve(file.originalPath)
114+
// 'istanbul' is default instrumenters
115+
const instrumenterLiteral = Object.keys(instrumenterOverrides).reduce((res, pattern) => {
125116
if (minimatch(file.originalPath, pattern, { dot: true })) {
126-
instrumenterLiteral = String(literal)
117+
return instrumenterOverrides[pattern]
127118
}
128-
})
119+
return res
120+
}, 'istanbul')
129121

130-
var instrumenterCreator = instrumenters[instrumenterLiteral]
131-
var constructOptions = instrumentersOptions[instrumenterLiteral] || {}
132-
var options = Object.assign({}, constructOptions)
133-
var codeGenerationOptions = null
122+
const instrumenterCreator = instrumenters[instrumenterLiteral]
123+
const constructOptions = instrumentersOptions[instrumenterLiteral] || {}
124+
let options = Object.assign({}, constructOptions)
125+
let codeGenerationOptions = null
134126
options.autoWrap = options.autoWrap || !options.noAutoWrap
135127

136128
if (file.sourceMap) {
@@ -148,15 +140,15 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
148140

149141
options = Object.assign({}, options, { codeGenerationOptions: codeGenerationOptions })
150142

151-
var instrumenter = instrumenterCreator(options)
143+
const instrumenter = instrumenterCreator(options)
152144
instrumenter.instrument(content, jsPath, function (err, instrumentedCode) {
153145
if (err) {
154146
log.error('%s\n at %s', err.message, file.originalPath)
155147
done(err.message)
156148
} else {
157149
if (file.sourceMap && instrumenter.lastSourceMap()) {
158150
log.debug('Adding source map to instrumented file for "%s".', file.originalPath)
159-
var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(instrumenter.lastSourceMap().toString()))
151+
const generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(instrumenter.lastSourceMap().toString()))
160152
generator.applySourceMap(new SourceMapConsumer(file.sourceMap))
161153
file.sourceMap = JSON.parse(generator.toString())
162154
instrumentedCode += '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,'
@@ -167,7 +159,7 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
167159
sourceMapStore.registerMap(jsPath, file.sourceMap)
168160

169161
if (includeAllSources) {
170-
var coverageObj
162+
let coverageObj
171163
// Check if the file coverage object is exposed from the instrumenter directly
172164
if (instrumenter.lastFileCoverage) {
173165
coverageObj = instrumenter.lastFileCoverage()
@@ -177,7 +169,7 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
177169

178170
// reset stateful regex
179171
coverageObjRegex.lastIndex = 0
180-
var coverageObjMatch = coverageObjRegex.exec(instrumentedCode)
172+
const coverageObjMatch = coverageObjRegex.exec(instrumentedCode)
181173
if (coverageObjMatch !== null) {
182174
coverageObj = JSON.parse(coverageObjMatch[0])
183175
globalCoverageMap.add(coverageObj)
@@ -198,7 +190,6 @@ function createCoveragePreprocessor (logger, helper, basePath, reporters, covera
198190

199191
createCoveragePreprocessor.$inject = [
200192
'logger',
201-
'helper',
202193
'config.basePath',
203194
'config.reporters',
204195
'config.coverageReporter'

‎lib/reporter.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ var path = require('path')
1414
var istanbulLibCoverage = require('istanbul-lib-coverage')
1515
var istanbulLibReport = require('istanbul-lib-report')
1616
var minimatch = require('minimatch')
17-
var _ = require('lodash')
1817

1918
var globalSourceMapStore = require('./source-map-store')
2019
var globalCoverageMap = require('./coverage-map')
@@ -180,7 +179,7 @@ var CoverageReporter = function (rootConfig, helper, logger, emitter) {
180179
dir = dir || 'coverage'
181180
subdir = subdir || browserName
182181

183-
if (_.isFunction(subdir)) {
182+
if (typeof subdir === 'function') {
184183
subdir = subdir(browserName)
185184
}
186185

@@ -266,9 +265,8 @@ var CoverageReporter = function (rootConfig, helper, logger, emitter) {
266265

267266
// // If reporting to console or in-memory skip directory creation
268267
var toDisk = !reporterConfig.type || !reporterConfig.type.match(/^(text|text-summary|in-memory)$/)
269-
var hasNoFile = _.isUndefined(reporterConfig.file)
270268

271-
if (!toDisk && hasNoFile) {
269+
if (!toDisk && reporterConfig.file === undefined) {
272270
tree.visit(report, context)
273271
return
274272
}

‎package.json

-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
"istanbul-lib-report": "^2.0.8",
2525
"istanbul-lib-source-maps": "^3.0.6",
2626
"istanbul-reports": "^2.2.4",
27-
"lodash": "^4.17.11",
2827
"minimatch": "^3.0.0",
2928
"source-map": "^0.5.1"
3029
},

‎test/preprocessor.spec.coffee

+10-11
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ vm = require 'vm'
22
util = require 'util'
33
path = require 'path'
44

5-
helper = {_: require 'lodash'}
65
coverageMap = require '../lib/coverage-map'
76

87
describe 'preprocessor', ->
@@ -39,7 +38,7 @@ describe 'preprocessor', ->
3938

4039

4140
it 'should not do anything if coverage reporter is not used', (done) ->
42-
process = createPreprocessor mockLogger, helper, null, ['dots', 'progress'], {}
41+
process = createPreprocessor mockLogger, null, ['dots', 'progress'], {}
4342
file = new File '/base/path/file.js'
4443

4544
process ORIGINAL_CODE, file, (preprocessedCode) ->
@@ -49,7 +48,7 @@ describe 'preprocessor', ->
4948

5049

5150
it 'should preprocess the code', (done) ->
52-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'], {}
51+
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'], {}
5352
file = new File '/base/path/file.js'
5453

5554
process ORIGINAL_CODE, file, (preprocessedCode) ->
@@ -66,7 +65,7 @@ describe 'preprocessor', ->
6665
fakeInstanbulLikeInstrumenter::instrument = (_a, _b, callback) ->
6766
callback()
6867
return
69-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
68+
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
7069
instrumenters:
7170
fakeInstanbulLike :
7271
Instrumenter : fakeInstanbulLikeInstrumenter
@@ -91,7 +90,7 @@ describe 'preprocessor', ->
9190
callback()
9291
return
9392

94-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
93+
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
9594
instrumenters:
9695
fakeInstanbulLike:
9796
Instrumenter: fakeInstanbulLikeInstrumenter
@@ -106,7 +105,7 @@ describe 'preprocessor', ->
106105
process ORIGINAL_COFFEE_CODE, file, done
107106

108107
it 'should not preprocess the coffee code', (done) ->
109-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
108+
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
110109
instrumenter:
111110
'**/*.coffee': 'istanbul'
112111
file = new File '/base/path/file.coffee'
@@ -123,14 +122,14 @@ describe 'preprocessor', ->
123122

124123
it 'should fail if invalid instrumenter provided', (done) ->
125124
work = ->
126-
createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
125+
createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
127126
instrumenter:
128127
'**/*.coffee': 'madeup'
129128
expect(work).to.throw()
130129
done()
131130

132131
it 'should add coverageMap when including all sources', (done) ->
133-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage'], { includeAllSources: true }
132+
process = createPreprocessor mockLogger, '/base/path', ['coverage'], { includeAllSources: true }
134133
file = new File '/base/path/file.js'
135134

136135
coverageMap.reset()
@@ -140,7 +139,7 @@ describe 'preprocessor', ->
140139
done()
141140

142141
it 'should not add coverageMap when not including all sources', (done) ->
143-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage'], { includeAllSources: false }
142+
process = createPreprocessor mockLogger, '/base/path', ['coverage'], { includeAllSources: false }
144143
file = new File '/base/path/file.js'
145144

146145
coverageMap.reset()
@@ -150,7 +149,7 @@ describe 'preprocessor', ->
150149
done()
151150

152151
it 'should not add coverageMap in the default state', (done) ->
153-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage'], {}
152+
process = createPreprocessor mockLogger, '/base/path', ['coverage'], {}
154153
file = new File '/base/path/file.js'
155154

156155
coverageMap.reset()
@@ -166,7 +165,7 @@ describe 'preprocessor', ->
166165
callback()
167166
return
168167

169-
process = createPreprocessor mockLogger, helper, '/base/path', ['coverage', 'progress'],
168+
process = createPreprocessor mockLogger, '/base/path', ['coverage', 'progress'],
170169
instrumenters:
171170
ibrik :
172171
Instrumenter : ibrikInstrumenter

‎test/reporter.spec.coffee

+11-13
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
# lib/reporters/Coverage.js module
33
#==============================================================================
44
describe 'reporter', ->
5-
_ = require 'lodash'
65
events = require 'events'
76
path = require 'path'
87

@@ -26,7 +25,6 @@ describe 'reporter', ->
2625

2726
mkdirIfNotExistsStub = sinon.stub()
2827
mockHelper =
29-
_: helper._
3028
isDefined: (v) -> helper.isDefined v
3129
merge: (v...) -> helper.merge v...
3230
mkdirIfNotExists: mkdirIfNotExistsStub
@@ -163,7 +161,7 @@ describe 'reporter', ->
163161
expect(createArgs[1].emitter).to.be.equal emitter
164162

165163
it 'should support a string for the subdir option', ->
166-
customConfig = _.merge {}, rootConfig,
164+
customConfig = helper.merge {}, rootConfig,
167165
coverageReporter:
168166
subdir: 'test'
169167

@@ -182,7 +180,7 @@ describe 'reporter', ->
182180
expect(mockPackageSummary.visit).to.have.been.called
183181

184182
it 'should support a function for the subdir option', ->
185-
customConfig = _.merge {}, rootConfig,
183+
customConfig = helper.merge {}, rootConfig,
186184
coverageReporter:
187185
subdir: (browserName) -> browserName.toLowerCase().split(/[ /-]/)[0]
188186

@@ -200,7 +198,7 @@ describe 'reporter', ->
200198
expect(mockPackageSummary.visit).to.have.been.called
201199

202200
it 'should support a specific dir and subdir per reporter', ->
203-
customConfig = _.merge {}, rootConfig,
201+
customConfig = helper.merge {}, rootConfig,
204202
coverageReporter:
205203
dir: 'useless'
206204
subdir: 'useless'
@@ -230,7 +228,7 @@ describe 'reporter', ->
230228
expect(mockPackageSummary.visit).to.have.been.called
231229

232230
it 'should fallback to the default dir/subdir if not provided', ->
233-
customConfig = _.merge {}, rootConfig,
231+
customConfig = helper.merge {}, rootConfig,
234232
coverageReporter:
235233
dir: 'defaultdir'
236234
subdir: 'defaultsubdir'
@@ -288,7 +286,7 @@ describe 'reporter', ->
288286
expect(mkdirIfNotExistsStub).to.have.been.calledTwice
289287

290288
it 'should support including all sources', ->
291-
customConfig = _.merge {}, rootConfig,
289+
customConfig = helper.merge {}, rootConfig,
292290
coverageReporter:
293291
dir: 'defaultdir'
294292
includeAllSources: true
@@ -304,7 +302,7 @@ describe 'reporter', ->
304302
expect(createCoverageMapStub).to.have.been.calledWith globalCoverageMapGetStub.returnValues[0]
305303

306304
it 'should not retrieve the coverageMap if we aren\'t including all sources', ->
307-
customConfig = _.merge {}, rootConfig,
305+
customConfig = helper.merge {}, rootConfig,
308306
coverageReporter:
309307
dir: 'defaultdir'
310308
includeAllSources: false
@@ -318,7 +316,7 @@ describe 'reporter', ->
318316
expect(globalCoverageMapGetStub).not.to.have.been.called
319317

320318
it 'should default to not including all sources', ->
321-
customConfig = _.merge {}, rootConfig,
319+
customConfig = helper.merge {}, rootConfig,
322320
coverageReporter:
323321
dir: 'defaultdir'
324322

@@ -337,7 +335,7 @@ describe 'reporter', ->
337335
functions: [50, 60]
338336
lines: [70, 80]
339337

340-
customConfig = _.merge {}, rootConfig,
338+
customConfig = helper.merge {}, rootConfig,
341339
coverageReporter:
342340
reporters: [
343341
{
@@ -364,7 +362,7 @@ describe 'reporter', ->
364362
statements: [10, 20]
365363
lines: [70, 80]
366364

367-
customConfig = _.merge {}, rootConfig,
365+
customConfig = helper.merge {}, rootConfig,
368366
coverageReporter:
369367
reporters: [
370368
{
@@ -390,7 +388,7 @@ describe 'reporter', ->
390388
expect(options.args[1].watermarks.lines).to.deep.equal(watermarks.lines)
391389

392390
it 'should log errors on low coverage and fail the build', ->
393-
customConfig = _.merge {}, rootConfig,
391+
customConfig = helper.merge {}, rootConfig,
394392
coverageReporter:
395393
check:
396394
each:
@@ -423,7 +421,7 @@ describe 'reporter', ->
423421
expect(results.exitCode).to.not.equal 0
424422

425423
it 'should not log errors on sufficient coverage and not fail the build', ->
426-
customConfig = _.merge {}, rootConfig,
424+
customConfig = helper.merge {}, rootConfig,
427425
coverageReporter:
428426
check:
429427
each:

0 commit comments

Comments
 (0)
Please sign in to comment.