-
Notifications
You must be signed in to change notification settings - Fork 290
/
JestExt.ts
622 lines (517 loc) · 20 KB
/
JestExt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import * as vscode from 'vscode'
import * as path from 'path'
import * as fs from 'fs'
import { Settings, ProjectWorkspace, JestTotalResults } from 'jest-editor-support'
import { matcher } from 'micromatch'
import * as decorations from './decorations'
import { IPluginSettings } from './IPluginSettings'
import * as status from './statusBar'
import {
TestReconciliationState,
TestResultProvider,
TestResult,
resultsWithLowerCaseWindowsDriveLetters,
} from './TestResults'
import { pathToJestPackageJSON, pathToJest, pathToConfig } from './helpers'
import { readFileSync } from 'fs'
import { CoverageMapProvider } from './Coverage'
import { updateDiagnostics, resetDiagnostics, failedSuiteCount } from './diagnostics'
import { DebugCodeLensProvider } from './DebugCodeLens'
import { DecorationOptions } from './types'
import { hasDocument, isOpenInMultipleEditors } from './editor'
import { CoverageOverlay } from './Coverage/CoverageOverlay'
import { JestProcess, JestProcessManager } from './JestProcessManagement'
export class JestExt {
private workspace: ProjectWorkspace
private jestSettings: Settings
private pluginSettings: IPluginSettings
coverageMapProvider: CoverageMapProvider
coverageOverlay: CoverageOverlay
testResultProvider: TestResultProvider
public debugCodeLensProvider: DebugCodeLensProvider
// So you can read what's going on
private channel: vscode.OutputChannel
// The ability to show fails in the problems section
private failDiagnostics: vscode.DiagnosticCollection
private passingItStyle: vscode.TextEditorDecorationType
private failingItStyle: vscode.TextEditorDecorationType
private skipItStyle: vscode.TextEditorDecorationType
private unknownItStyle: vscode.TextEditorDecorationType
private parsingTestFile = false
// We have to keep track of our inline assert fails to remove later
failingAssertionDecorators: { [fileName: string]: vscode.TextEditorDecorationType[] }
private jestProcessManager: JestProcessManager
private jestProcess: JestProcess
private clearOnNextInput: boolean
constructor(workspace: ProjectWorkspace, outputChannel: vscode.OutputChannel, pluginSettings: IPluginSettings) {
this.workspace = workspace
this.channel = outputChannel
this.failingAssertionDecorators = {}
this.failDiagnostics = vscode.languages.createDiagnosticCollection('Jest')
this.clearOnNextInput = true
this.jestSettings = new Settings(workspace)
this.pluginSettings = pluginSettings
this.coverageMapProvider = new CoverageMapProvider()
this.coverageOverlay = new CoverageOverlay(this.coverageMapProvider, pluginSettings.showCoverageOnLoad)
this.testResultProvider = new TestResultProvider()
this.debugCodeLensProvider = new DebugCodeLensProvider(this.testResultProvider, pluginSettings.enableCodeLens)
this.jestProcessManager = new JestProcessManager({
projectWorkspace: workspace,
runAllTestsFirstInWatchMode: this.pluginSettings.runAllTestsFirst,
})
this.getSettings()
// The theme stuff
this.setupDecorators()
// The bottom bar thing
this.setupStatusBar()
//reset the jest diagnostics
resetDiagnostics(this.failDiagnostics)
// If we should start the process by default, do so
if (this.pluginSettings.autoEnable) {
this.startProcess()
} else {
this.channel.appendLine('Skipping initial Jest runner process start.')
}
}
private handleStdErr(error: Buffer) {
const message = error.toString()
if (this.shouldIgnoreOutput(message)) {
return
}
// The "tests are done" message comes through stdErr
// We want to use this as a marker that the console should
// be cleared, as the next input will be from a new test run.
if (this.clearOnNextInput) {
this.clearOnNextInput = false
this.parsingTestFile = false
this.channel.clear()
}
// thanks Qix, http://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings
const noANSI = message.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, '')
if (noANSI.includes('snapshot test failed')) {
this.detectedSnapshotErrors()
}
this.channel.appendLine(noANSI)
}
private assignHandlers(jestProcess) {
jestProcess
.onJestEditorSupportEvent('executableJSON', (data: JestTotalResults) => {
this.updateWithData(data)
})
.onJestEditorSupportEvent('executableOutput', (output: string) => {
if (!this.shouldIgnoreOutput(output)) {
this.channel.appendLine(output)
}
})
.onJestEditorSupportEvent('executableStdErr', (error: Buffer) => this.handleStdErr(error))
.onJestEditorSupportEvent('nonTerminalError', (error: string) => {
this.channel.appendLine(`Received an error from Jest Runner: ${error.toString()}`)
})
.onJestEditorSupportEvent('exception', result => {
this.channel.appendLine(`\nException raised: [${result.type}]: ${result.message}\n`)
})
.onJestEditorSupportEvent('terminalError', (error: string) => {
this.channel.appendLine('\nException raised: ' + error)
})
}
public startProcess() {
if (this.jestProcessManager.numberOfProcesses > 0) {
return
}
if (this.pluginSettings.runAllTestsFirst) {
this.testsHaveStartedRunning()
}
this.jestProcess = this.jestProcessManager.startJestProcess({
watch: true,
keepAlive: true,
exitCallback: (jestProcess, jestProcessInWatchMode) => {
if (jestProcessInWatchMode) {
this.jestProcess = jestProcessInWatchMode
this.channel.appendLine('Finished running all tests. Starting watch mode.')
status.running('Starting watch mode')
this.assignHandlers(this.jestProcess)
} else {
status.stopped()
if (!jestProcess.stopRequested) {
this.channel.appendLine(
'Starting Jest in Watch mode failed too many times and has been stopped. Please check your system configuration.'
)
}
}
},
})
this.assignHandlers(this.jestProcess)
}
public stopProcess() {
this.channel.appendLine('Closing Jest')
this.jestProcessManager.stopAll()
status.stopped()
}
private getSettings() {
this.getJestVersion(jestVersionMajor => {
if (jestVersionMajor < 20) {
vscode.window.showErrorMessage(
'This extension relies on Jest 20+ features, it will continue to work, but some features may not work correctly.'
)
}
this.workspace.localJestMajorVersion = jestVersionMajor
})
// Do nothing for the minute, the above ^ can come back once
// https://github.com/facebook/jest/pull/3592 is deployed
try {
this.jestSettings.getConfig(() => {})
} catch (error) {
console.log('[vscode-jest] Getting Jest config crashed, likely due to Jest version being below version 20.')
}
}
private detectedSnapshotErrors() {
if (!this.pluginSettings.enableSnapshotUpdateMessages) {
return
}
vscode.window
.showInformationMessage('Would you like to update your Snapshots?', { title: 'Replace them' })
.then(response => {
// No response == cancel
if (response) {
this.jestProcess.runJestWithUpdateForSnapshots(() => {
if (this.pluginSettings.restartJestOnSnapshotUpdate) {
this.jestProcessManager.stopJestProcess(this.jestProcess).then(() => {
this.startProcess()
})
vscode.window.showInformationMessage('Updated Snapshots and restarted Jest.')
} else {
vscode.window.showInformationMessage('Updated Snapshots. It will show in your next test run.')
}
})
}
})
}
public triggerUpdateDecorations(editor: vscode.TextEditor) {
this.coverageOverlay.updateVisibleEditors()
if (!this.canUpdateDecorators(editor)) {
return
}
// OK - lets go
this.parsingTestFile = true
this.updateDotDecorators(editor)
this.parsingTestFile = false
}
public triggerUpdateSettings(updatedSettings: IPluginSettings) {
this.pluginSettings = updatedSettings
this.workspace.rootPath = updatedSettings.rootPath
this.workspace.pathToJest = pathToJest(updatedSettings)
this.workspace.pathToConfig = pathToConfig(updatedSettings)
this.jestSettings = new Settings(this.workspace)
this.coverageOverlay.enabled = updatedSettings.showCoverageOnLoad
this.debugCodeLensProvider.enabled = updatedSettings.enableCodeLens
this.stopProcess()
setTimeout(() => {
this.startProcess()
}, 500)
}
private updateDotDecorators(editor: vscode.TextEditor) {
const filePath = editor.document.fileName
const testResults = this.testResultProvider.getSortedResults(filePath)
// Dots
const styleMap = [
{ data: testResults.success, decorationType: this.passingItStyle, state: TestReconciliationState.KnownSuccess },
{ data: testResults.fail, decorationType: this.failingItStyle, state: TestReconciliationState.KnownFail },
{ data: testResults.skip, decorationType: this.skipItStyle, state: TestReconciliationState.KnownSkip },
{ data: testResults.unknown, decorationType: this.unknownItStyle, state: TestReconciliationState.Unknown },
]
styleMap.forEach(style => {
const decorators = this.generateDotsForItBlocks(style.data, style.state)
editor.setDecorations(style.decorationType, decorators)
})
// Debug CodeLens
this.debugCodeLensProvider.didChange()
// Inline error messages
this.resetInlineErrorDecorators(editor)
if (this.pluginSettings.enableInlineErrorMessages) {
const fileName = editor.document.fileName
testResults.fail.forEach(a => {
const { style, decorator } = this.generateInlineErrorDecorator(fileName, a)
editor.setDecorations(style, [decorator])
})
}
}
private resetInlineErrorDecorators(editor: vscode.TextEditor) {
if (!this.failingAssertionDecorators[editor.document.fileName]) {
this.failingAssertionDecorators[editor.document.fileName] = []
return
}
if (isOpenInMultipleEditors(editor.document)) {
return
}
this.failingAssertionDecorators[editor.document.fileName].forEach(element => {
element.dispose()
})
this.failingAssertionDecorators[editor.document.fileName] = []
}
private generateInlineErrorDecorator(fileName: string, test: TestResult) {
const errorMessage = test.terseMessage || test.shortMessage
const decorator = {
range: new vscode.Range(test.lineNumberOfError, 0, test.lineNumberOfError, 0),
hoverMessage: errorMessage,
}
// We have to make a new style for each unique message, this is
// why we have to remove off of them beforehand
const style = decorations.failingAssertionStyle(errorMessage)
this.failingAssertionDecorators[fileName].push(style)
return { style, decorator }
}
canUpdateDecorators(editor: vscode.TextEditor) {
const atEmptyScreen = !editor
if (atEmptyScreen) {
return false
}
const inSettings = !editor.document
if (inSettings) {
return false
}
if (this.parsingTestFile) {
return false
}
const isATestFile = this.wouldJestRunURI(editor.document.uri)
return isATestFile
}
private wouldJestRunURI(uri: vscode.Uri) {
const filePath = uri.fsPath
const globs: string[] = (this.jestSettings.settings as any).testMatch
if (globs && globs.length) {
const matchers = globs.map(each => matcher(each, { dot: true }))
const matched = matchers.some(isMatch => isMatch(filePath))
return matched
}
const root = this.pluginSettings.rootPath
let relative = path.normalize(path.relative(root, filePath))
// replace windows path separator with normal slash
if (path.sep === '\\') {
relative = relative.replace(/\\/g, '/')
}
const testRegex = new RegExp(this.jestSettings.settings.testRegex)
const matches = relative.match(testRegex)
return matches && matches.length > 0
}
private setupStatusBar() {
status.initial()
}
private setupDecorators() {
this.passingItStyle = decorations.passingItName()
this.failingItStyle = decorations.failingItName()
this.skipItStyle = decorations.skipItName()
this.unknownItStyle = decorations.notRanItName()
}
private shouldIgnoreOutput(text: string): boolean {
// this fails when snapshots change - to be revised - returning always false for now
return text.includes('Watch Usage')
}
private testsHaveStartedRunning() {
this.channel.clear()
status.running('initial full test run')
}
private updateWithData(data: JestTotalResults) {
const normalizedData = resultsWithLowerCaseWindowsDriveLetters(data)
this.coverageMapProvider.update(normalizedData.coverageMap)
const statusList = this.testResultProvider.updateTestResults(normalizedData)
updateDiagnostics(statusList, this.failDiagnostics)
const failedFileCount = failedSuiteCount(this.failDiagnostics)
if (failedFileCount <= 0 && normalizedData.success) {
status.success()
} else {
status.failed(` (${failedFileCount} test suite${failedFileCount > 1 ? 's' : ''} failed)`)
}
for (const editor of vscode.window.visibleTextEditors) {
this.triggerUpdateDecorations(editor)
}
this.clearOnNextInput = true
}
private generateDotsForItBlocks(blocks: TestResult[], state: TestReconciliationState): DecorationOptions[] {
const nameForState = {
[TestReconciliationState.KnownSuccess]: 'Passed',
[TestReconciliationState.KnownFail]: 'Failed',
[TestReconciliationState.KnownSkip]: 'Skipped',
[TestReconciliationState.Unknown]: 'Test has not run yet, due to Jest only running tests related to changes.',
}
return blocks.map(it => {
return {
range: new vscode.Range(it.start.line, it.start.column, it.start.line, it.start.column + 1),
hoverMessage: nameForState[state],
/* ERROR: this needs to include all ancestor describe block names as well!
in code bellow it block has identifier = 'aaa bbb ccc': but name is only 'ccc'
describe('aaa', () => {
describe('bbb', () => {
it('ccc', () => {
});
});
});
*/
identifier: it.name,
}
})
}
public deactivate() {
this.jestProcessManager.stopAll()
}
private getJestVersion(version: (v: number) => void) {
let ver = 18 // default to the last pre-20 release if nothing else can be determined
const packageJSON = pathToJestPackageJSON(this.pluginSettings)
if (packageJSON) {
const contents = readFileSync(packageJSON, 'utf8')
const packageMetadata = JSON.parse(contents)
if (packageMetadata['version']) {
ver = parseInt(packageMetadata['version'])
}
}
version(ver)
}
/**
* Primitive way to resolve path to jest.js
*/
private resolvePathToJestBin() {
let jest = this.workspace.pathToJest
if (!path.isAbsolute(jest)) {
jest = path.join(vscode.workspace.rootPath, jest)
}
const basename = path.basename(jest)
switch (basename) {
case 'jest.js': {
return jest
}
case 'jest.cmd': {
/* i need to extract '..\jest-cli\bin\jest.js' from line 2
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "%~dp0\..\jest-cli\bin\jest.js" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "%~dp0\..\jest-cli\bin\jest.js" %*
)
*/
const line = fs.readFileSync(jest, 'utf8').split('\n')[1]
const match = /^\s*"[^"]+"\s+"%~dp0\\([^"]+)"/.exec(line)
return path.join(path.dirname(jest), match[1])
}
case 'jest': {
/* file without extension uses first line as file type
in case of node script i can use this file directly,
in case of linux shell script i need to extract path from line 9
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../jest-cli/bin/jest.js" "$@"
ret=$?
else
node "$basedir/../jest-cli/bin/jest.js" "$@"
ret=$?
fi
exit $ret
*/
const lines = fs.readFileSync(jest, 'utf8').split('\n')
switch (lines[0]) {
case '#!/usr/bin/env node': {
return jest
}
case '#!/bin/sh': {
const line = lines[8]
const match = /^\s*"[^"]+"\s+"$basedir\/([^"]+)"/.exec(line)
if (match) {
return path.join(path.dirname(jest), match[1])
}
break
}
}
break
}
}
vscode.window.showErrorMessage('Cannot find jest.js file!')
return undefined
}
public runTest = (fileName: string, identifier: string) => {
const restart = this.jestProcessManager.numberOfProcesses > 0
this.jestProcessManager.stopAll()
const program = this.resolvePathToJestBin()
if (!program) {
console.log("Could not find Jest's CLI path")
return
}
const escapedIdentifier = JSON.stringify(identifier).slice(1, -1)
const args = ['--runInBand', fileName, '--testNamePattern', escapedIdentifier]
if (this.pluginSettings.pathToConfig.length) {
args.push('--config', this.pluginSettings.pathToConfig)
}
const port = Math.floor(Math.random() * 20000) + 10000
const configuration = {
name: 'TestRunner',
type: 'node',
request: 'launch',
program,
args,
runtimeArgs: ['--inspect-brk=' + port],
port,
protocol: 'inspector',
console: 'integratedTerminal',
smartStep: true,
sourceMaps: true,
}
const handle = vscode.debug.onDidTerminateDebugSession(_ => {
handle.dispose()
if (restart) {
this.startProcess()
}
})
vscode.debug.startDebugging(vscode.workspace.workspaceFolders[0], configuration)
}
onDidCloseTextDocument(document: vscode.TextDocument) {
this.removeCachedTestResults(document)
this.removeCachedDecorationTypes(document)
}
removeCachedTestResults(document: vscode.TextDocument) {
if (!document || document.isUntitled) {
return
}
const filePath = document.fileName
this.testResultProvider.removeCachedResults(filePath)
}
removeCachedDecorationTypes(document: vscode.TextDocument) {
if (!document || !document.fileName) {
return
}
delete this.failingAssertionDecorators[document.fileName]
}
onDidChangeActiveTextEditor(editor: vscode.TextEditor) {
if (!hasDocument(editor)) {
return
}
this.triggerUpdateDecorations(editor)
}
/**
* This event is fired with the document not dirty when:
* - before the onDidSaveTextDocument event
* - the document was changed by an external editor
*/
onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) {
if (event.document.isDirty) {
return
}
if (event.document.uri.scheme === 'git') {
return
}
// Ignore a clean file with a change:
if (event.contentChanges.length > 0) {
return
}
this.removeCachedTestResults(event.document)
for (const editor of vscode.window.visibleTextEditors) {
if (editor.document === event.document) {
this.triggerUpdateDecorations(editor)
}
}
}
toggleCoverageOverlay() {
this.coverageOverlay.toggleVisibility()
}
}