-
Notifications
You must be signed in to change notification settings - Fork 293
/
Copy pathtest-item-data.ts
833 lines (762 loc) · 26.7 KB
/
test-item-data.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
import * as vscode from 'vscode';
import { extensionId } from '../appGlobals';
import { JestRunEvent, RunEventBase } from '../JestExt';
import { TestSuiteResult } from '../TestResults';
import * as path from 'path';
import { JestExtRequestType } from '../JestExt/process-session';
import { ItBlock, TestAssertionStatus } from 'jest-editor-support';
import { ContainerNode, DataNode, NodeType, ROOT_NODE_NAME } from '../TestResults/match-node';
import { Logging } from '../logging';
import { TestSuitChangeEvent } from '../TestResults/test-result-events';
import { Debuggable, ItemCommand, TestItemData } from './types';
import { JestTestProviderContext, JestTestRun, JestTestRunOptions } from './test-provider-helper';
import { JestProcessInfo, JestProcessRequest } from '../JestProcessManagement';
import { GENERIC_ERROR, getExitErrorDef, LONG_RUNNING_TESTS } from '../errors';
import { JestExtOutput } from '../JestExt/output-terminal';
import { tiContextManager } from './test-item-context-manager';
import { toAbsoluteRootPath } from '../helpers';
interface JestRunnable {
getJestRunRequest: () => JestExtRequestType;
}
interface WithUri {
uri: vscode.Uri;
}
type JestTestRunRequest = JestExtRequestType & { run: JestTestRun };
type TypedRunEvent = RunEventBase & { type: string };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isJestTestRunRequest = (arg: any): arg is JestTestRunRequest =>
arg.run instanceof JestTestRun;
abstract class TestItemDataBase implements TestItemData, JestRunnable, WithUri {
item!: vscode.TestItem;
log: Logging;
constructor(public context: JestTestProviderContext, name: string) {
this.log = context.ext.loggingFactory.create(name);
}
get uri(): vscode.Uri {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.item.uri!;
}
deepItemState(
item: vscode.TestItem | undefined,
setState: (item: vscode.TestItem) => void
): void {
if (!item) {
this.log('warn', '<deepItemState>: no item to set state');
return;
}
setState(item);
item.children.forEach((child) => this.deepItemState(child, setState));
}
isTestNameResolved() {
return true;
}
scheduleTest(run: JestTestRun, itemCommand?: ItemCommand): void {
if (!this.isTestNameResolved()) {
const parent = this.item.parent && this.context.getData(this.item.parent);
if (parent) {
return parent.scheduleTest(run, itemCommand);
}
this.context.output.write(`running an unresolved parameterized test might fail`, 'warn');
}
const jestRequest = this.getJestRunRequest(itemCommand);
run.item = this.item;
this.deepItemState(this.item, run.enqueued);
const process = this.context.ext.session.scheduleProcess({
...jestRequest,
run,
});
if (!process) {
const msg = `failed to schedule test for ${this.item.id}`;
run.errored(this.item, new vscode.TestMessage(msg));
run.write(msg, 'error');
run.end();
}
}
runItemCommand(command: ItemCommand): void | Promise<void> {
switch (command) {
case ItemCommand.updateSnapshot: {
const request = new vscode.TestRunRequest([this.item]);
const run = this.context.createTestRun(request, {
name: `${command}-${this.item.id}`,
});
this.scheduleTest(run, command);
break;
}
case ItemCommand.viewSnapshot: {
return this.viewSnapshot().catch((e) => this.log('error', e));
}
case ItemCommand.revealOutput: {
return this.context.output.show();
}
}
}
viewSnapshot(): Promise<void> {
return Promise.reject(`viewSnapshot is not supported for ${this.item.id}`);
}
abstract getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType;
}
interface SnapshotItemCollection {
viewable: vscode.TestItem[];
updatable: vscode.TestItem[];
}
/**
* Goal of this class is to manage the TestItem hierarchy reflects DocumentRoot path. It is responsible
* to create DocumentRoot for each test file by listening to the TestResultEvents.
*/
export class WorkspaceRoot extends TestItemDataBase {
private testDocuments: Map<string, TestDocumentRoot>;
private listeners: vscode.Disposable[];
private cachedRun: Map<string, JestTestRun>;
constructor(context: JestTestProviderContext) {
super(context, 'WorkspaceRoot');
this.item = this.createTestItem();
this.testDocuments = new Map();
this.listeners = [];
this.cachedRun = new Map();
this.registerEvents();
}
createTestItem(): vscode.TestItem {
const item = this.context.createTestItem(
`${extensionId}:${this.context.ext.workspace.name}`,
this.context.ext.workspace.name,
this.context.ext.workspace.uri,
this,
undefined,
['run']
);
item.description = `(${this.context.ext.settings.autoRun.mode})`;
item.canResolveChildren = true;
return item;
}
getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType {
const transform = (request: JestProcessRequest) => {
request.schedule.queue = 'blocking-2';
return request;
};
const updateSnapshot = itemCommand === ItemCommand.updateSnapshot;
return { type: 'all-tests', updateSnapshot, transform };
}
discoverTest(run: JestTestRun): void {
const testList = this.context.ext.testResultProvider.getTestList();
// only trigger update when testList is not empty because it's possible test-list is not available yet,
// in such case we should just wait for the testListUpdated event to trigger the update
if (testList.length > 0) {
this.onTestListUpdated(testList, run);
} else {
run.end();
this.item.canResolveChildren = false;
}
}
// test result event handling
private registerEvents = (): void => {
this.listeners = [
this.context.ext.testResultProvider.events.testListUpdated.event(this.onTestListUpdated),
this.context.ext.testResultProvider.events.testSuiteChanged.event(this.onTestSuiteChanged),
this.context.ext.sessionEvents.onRunEvent.event(this.onRunEvent),
];
};
private unregisterEvents = (): void => {
this.listeners.forEach((l) => l.dispose());
this.listeners.length = 0;
};
private createRun = (options?: JestTestRunOptions): JestTestRun => {
const item = options?.item ?? this.item;
const request = new vscode.TestRunRequest([item]);
return this.context.createTestRun(request, {
...options,
name: options?.name ?? item.id,
item,
});
};
private addFolder = (parent: FolderData | undefined, folderName: string): FolderData => {
const p = parent ?? this;
const uri = FolderData.makeUri(p.item, folderName);
return (
this.context.getChildData<FolderData>(p.item, uri.fsPath) ??
new FolderData(this.context, folderName, p.item)
);
};
private addPath = (absoluteFileName: string): FolderData | undefined => {
const absoluteRoot = toAbsoluteRootPath(
this.context.ext.workspace,
this.context.ext.settings.rootPath
);
const relativePath = path.relative(absoluteRoot, absoluteFileName);
const folders = relativePath.split(path.sep).slice(0, -1);
return folders.reduce(this.addFolder, undefined);
};
/**
* create a test item hierarchy for the given the test file based on its relative path. If the file is not
* a test file, exception will be thrown.
*/
private addTestFile = (
absoluteFileName: string,
onTestDocument: (doc: TestDocumentRoot) => void
): TestDocumentRoot => {
const parent = this.addPath(absoluteFileName) ?? this;
let docRoot = this.context.getChildData<TestDocumentRoot>(parent.item, absoluteFileName);
if (!docRoot) {
docRoot = this.testDocuments.get(absoluteFileName);
if (docRoot) {
parent.item.children.add(docRoot.item);
} else {
docRoot = new TestDocumentRoot(
this.context,
vscode.Uri.file(absoluteFileName),
parent.item
);
}
}
this.testDocuments.set(absoluteFileName, docRoot);
onTestDocument(docRoot);
return docRoot;
};
/**
* When test list updated, rebuild the whole testItem tree for all the test files (DocumentRoot).
* But will reuse the existing test document from cache (testDocuments) to preserve info
* such as parsed result that could be stored before test list update
*/
private onTestListUpdated = (
absoluteFileNames: string[] | undefined,
run?: JestTestRun
): void => {
this.item.children.replace([]);
const testRoots: TestDocumentRoot[] = [];
const aRun = run ?? this.createRun();
absoluteFileNames?.forEach((f) =>
this.addTestFile(f, (testRoot) => {
testRoot.updateResultState(aRun);
testRoots.push(testRoot);
})
);
//sync testDocuments
this.testDocuments.clear();
testRoots.forEach((t) => this.testDocuments.set(t.item.id, t));
aRun.end();
this.item.canResolveChildren = false;
};
/**
* invoked when external test result changed, this could be caused by the watch-mode or on-demand test run, includes vscode's runTest.
* We will try to find the run based on the event's id, if found, means a vscode runTest initiated such run, will use that run to
* ask all touched DocumentRoot to refresh both the test items and their states.
*
* @param event
*/
private onTestSuiteChanged = (event: TestSuitChangeEvent): void => {
switch (event.type) {
case 'assertions-updated': {
const run = this.getJestRun(event.process) ?? this.createRunForEvent(event);
this.log(
'debug',
`update status from run "${event.process.id}": ${event.files.length} files`
);
event.files.forEach((f) => this.addTestFile(f, (testRoot) => testRoot.discoverTest(run)));
run.end();
break;
}
case 'result-matched': {
const snapshotItems: SnapshotItemCollection = {
viewable: [],
updatable: [],
};
this.addTestFile(event.file, (testRoot) => {
testRoot.onTestMatched();
testRoot.gatherSnapshotItems(snapshotItems);
});
this.updateSnapshotContext(snapshotItems);
break;
}
case 'result-match-failed': {
const snapshotItems: SnapshotItemCollection = {
viewable: [],
updatable: [],
};
this.addTestFile(event.file, (testRoot) => {
testRoot.discoverTest(undefined, event.sourceContainer);
testRoot.gatherSnapshotItems(snapshotItems);
});
this.updateSnapshotContext(snapshotItems);
break;
}
}
};
private updateSnapshotContext(snapshotItems: SnapshotItemCollection): void {
tiContextManager.setItemContext({
workspace: this.context.ext.workspace,
key: 'jest.editor-view-snapshot',
itemIds: snapshotItems.viewable.map((item) => item.id),
});
const getAllIds = (item: vscode.TestItem, allIds: Set<string>): void => {
if (allIds.has(item.id)) {
return;
}
allIds.add(item.id);
if (item.parent) {
getAllIds(item.parent, allIds);
}
};
const allIds = new Set<string>();
snapshotItems.updatable.forEach((item) => getAllIds(item, allIds));
tiContextManager.setItemContext({
workspace: this.context.ext.workspace,
key: 'jest.editor-update-snapshot',
itemIds: [...allIds],
});
}
/** get test item from jest process. If running tests from source file, will return undefined */
private getItemFromProcess = (process: JestProcessInfo): vscode.TestItem | undefined => {
// the TestExplorer triggered run should already have item associated
if (isJestTestRunRequest(process.request) && process.request.run.item) {
return process.request.run.item;
}
// should only come here for autoRun processes
let fileName;
switch (process.request.type) {
case 'watch-tests':
case 'watch-all-tests':
case 'all-tests':
return this.item;
case 'by-file':
fileName = process.request.testFileName;
break;
case 'by-file-pattern':
fileName = process.request.testFileNamePattern;
break;
default:
throw new Error(`unsupported external process type ${process.request.type}`);
}
return this.testDocuments.get(fileName)?.item;
};
private createRunForEvent = (event: TypedRunEvent): JestTestRun => {
const item = this.getItemFromProcess(event.process) ?? this.item;
const name = isJestTestRunRequest(event.process.request)
? event.process.request.run.name
: `${event.type}:${event.process.id}`;
const run = this.createRun({
name,
item,
onEnd: () => this.cachedRun.delete(event.process.id),
});
this.cachedRun.set(event.process.id, run);
return run;
};
/** return a valid run from process or process-run-cache. return undefined if run is closed. */
private getJestRun = (process: JestProcessInfo): JestTestRun | undefined => {
if (isJestTestRunRequest(process.request) && !process.request.run.isClosed()) {
return process.request.run;
}
const run = this.cachedRun.get(process.id);
if (run?.isClosed()) {
this.cachedRun.delete(process.id);
return;
}
return run;
};
private runLog(type: string): void {
const d = new Date();
this.context.output.write(`> Test run ${type} at ${d.toLocaleString()} <\r\n`, [
'bold',
'new-line',
]);
}
private writer(run?: JestTestRun): JestExtOutput {
return run ?? this.context.output;
}
private onRunEvent = (event: JestRunEvent) => {
if (event.process.request.type === 'not-test') {
return;
}
let run = this.getJestRun(event.process);
try {
switch (event.type) {
case 'scheduled': {
if (!run) {
run = this.createRunForEvent(event);
this.deepItemState(run.item, run.enqueued);
}
if (this.context.ext.settings.autoClearTerminal === true) {
this.context.output.clear();
}
break;
}
case 'data': {
const text = event.raw ?? event.text;
if (text && text.length > 0) {
const opt = event.isError ? 'error' : event.newLine ? 'new-line' : undefined;
this.writer(run).write(text, opt);
}
break;
}
case 'start': {
run = run ?? this.createRunForEvent(event);
this.deepItemState(run.item, run.started);
if (this.context.ext.settings.autoClearTerminal === true) {
this.context.output.clear();
}
this.runLog('started');
break;
}
case 'end': {
if (event.error) {
this.writer(run).write(event.error, 'error');
}
this.runLog('finished');
run?.end();
break;
}
case 'exit': {
if (event.error) {
run = run ?? this.createRunForEvent(event);
const type = getExitErrorDef(event.code) ?? GENERIC_ERROR;
run.write(event.error, type);
if (run.item) {
run.errored(run.item, new vscode.TestMessage(event.error));
}
}
this.runLog('exited');
run?.end();
break;
}
case 'long-run': {
this.writer(run).write(
`Long Running Tests Warning: Tests exceeds ${event.threshold}ms threshold. Please reference Troubleshooting if this is not expected`,
LONG_RUNNING_TESTS
);
break;
}
}
} catch (err) {
this.log('error', `<onRunEvent> ${event.type} failed:`, err);
this.context.output.write(`<onRunEvent> ${event.type} failed: ${err}`, 'error');
}
};
dispose(): void {
this.unregisterEvents();
this.cachedRun.forEach((run) => run.end());
}
}
export class FolderData extends TestItemDataBase {
static makeUri = (parent: vscode.TestItem, folderName: string): vscode.Uri => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return vscode.Uri.joinPath(parent.uri!, folderName);
};
constructor(
readonly context: JestTestProviderContext,
readonly name: string,
parent: vscode.TestItem
) {
super(context, 'FolderData');
this.item = this.createTestItem(name, parent);
}
private createTestItem(name: string, parent: vscode.TestItem) {
const uri = FolderData.makeUri(parent, name);
const item = this.context.createTestItem(uri.fsPath, name, uri, this, parent, ['run']);
item.canResolveChildren = false;
return item;
}
getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType {
const updateSnapshot = itemCommand === ItemCommand.updateSnapshot;
return {
type: 'by-file-pattern',
updateSnapshot,
testFileNamePattern: this.uri.fsPath,
};
}
}
type ItemNodeType = NodeType<ItBlock | TestAssertionStatus>;
type ItemDataNodeType = DataNode<ItBlock | TestAssertionStatus>;
const isDataNode = (arg: ItemNodeType): arg is ItemDataNodeType =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(arg as any).data != null;
const isAssertDataNode = (arg: ItemNodeType): arg is DataNode<TestAssertionStatus> =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
isDataNode(arg) && (arg.data as any).fullName;
const isEmpty = (node?: ItemNodeType): boolean => {
if (!node) {
return true;
}
if (isDataNode(node)) {
return false;
}
if (
(node.childData && node.childData.length > 0) ||
(node.childContainers && node.childContainers.length > 0)
) {
return false;
}
return true;
};
// type AssertNode = NodeType<TestAssertionStatus>;
abstract class TestResultData extends TestItemDataBase {
constructor(readonly context: JestTestProviderContext, name: string) {
super(context, name);
}
updateItemState(
run: JestTestRun,
result?: TestSuiteResult | TestAssertionStatus,
errorLocation?: vscode.Location
): void {
if (!result) {
return;
}
const status = result.status;
switch (status) {
case 'KnownSuccess':
run.passed(this.item);
break;
case 'KnownSkip':
case 'KnownTodo':
run.skipped(this.item);
break;
case 'KnownFail': {
if (this.context.ext.settings.testExplorer.showInlineError) {
const message = new vscode.TestMessage(result.message);
if (errorLocation) {
message.location = errorLocation;
}
run.failed(this.item, message);
} else {
run.failed(this.item, []);
}
break;
}
}
}
makeTestId(fileUri: vscode.Uri, target?: ItemNodeType, extra?: string): string {
const parts = [fileUri.fsPath];
if (target && target.name !== ROOT_NODE_NAME) {
parts.push(target.fullName);
}
if (extra) {
parts.push(extra);
}
return parts.join('#');
}
isSameId(id1: string, id2: string): boolean {
if (id1 === id2) {
return true;
}
// truncate the last "extra-id" added for duplicate test names before comparing
const truncateExtra = (id: string): string => id.replace(/(.*)(#[0-9]+$)/, '$1');
return truncateExtra(id1) === truncateExtra(id2);
}
syncChildNodes(node: ItemNodeType): void {
const testId = this.makeTestId(this.uri, node);
if (!this.isSameId(testId, this.item.id)) {
this.item.error = 'invalid node';
return;
}
this.item.error = undefined;
if (!isDataNode(node)) {
const idMap = [...node.childContainers, ...node.childData]
.flatMap((n) => n.getAll() as ItemDataNodeType[])
.reduce((map, node) => {
const id = this.makeTestId(this.uri, node);
map.set(id, map.get(id)?.concat(node) ?? [node]);
return map;
}, new Map<string, ItemDataNodeType[]>());
const newItems: vscode.TestItem[] = [];
idMap.forEach((nodes, id) => {
if (nodes.length > 1) {
// duplicate names found, append index to make a unique id: re-create the item with new id
nodes.forEach((n, idx) => {
newItems.push(new TestData(this.context, this.uri, n, this.item, `${idx}`).item);
});
return;
}
let cItem = this.item.children.get(id);
if (cItem) {
this.context.getData<TestData>(cItem)?.updateNode(nodes[0]);
} else {
cItem = new TestData(this.context, this.uri, nodes[0], this.item).item;
}
newItems.push(cItem);
});
this.item.children.replace(newItems);
} else {
this.item.children.replace([]);
}
}
createLocation(uri: vscode.Uri, zeroBasedLine = 0): vscode.Location {
return new vscode.Location(
uri,
new vscode.Range(new vscode.Position(zeroBasedLine, 0), new vscode.Position(zeroBasedLine, 0))
);
}
forEachChild(onTestData: (child: TestData) => void): void {
this.item.children.forEach((childItem) => {
const child = this.context.getData<TestData>(childItem);
if (child) {
onTestData(child);
}
});
}
}
export class TestDocumentRoot extends TestResultData {
constructor(
readonly context: JestTestProviderContext,
fileUri: vscode.Uri,
parent: vscode.TestItem
) {
super(context, 'TestDocumentRoot');
this.item = this.createTestItem(fileUri, parent);
}
private createTestItem(fileUri: vscode.Uri, parent: vscode.TestItem): vscode.TestItem {
const item = this.context.createTestItem(
this.makeTestId(fileUri),
path.basename(fileUri.fsPath),
fileUri,
this,
parent
);
item.canResolveChildren = true;
return item;
}
discoverTest = (run?: JestTestRun, parsedRoot?: ContainerNode<ItBlock>): void => {
this.createChildItems(parsedRoot);
if (run) {
this.updateResultState(run);
}
};
private createChildItems = (parsedRoot?: ContainerNode<ItBlock>): void => {
const container =
this.context.ext.testResultProvider.getTestSuiteResult(this.item.id)?.assertionContainer ??
parsedRoot;
if (!container) {
this.item.children.replace([]);
} else {
this.syncChildNodes(container);
}
this.item.canResolveChildren = false;
};
public updateResultState(run: JestTestRun): void {
const suiteResult = this.context.ext.testResultProvider.getTestSuiteResult(this.item.id);
// only update suite status if the assertionContainer is empty, which can occur when
// test file has syntax error or failed to run for whatever reason.
// In this case we should mark the suite itself as TestExplorer won't be able to
// aggregate from the children list
if (isEmpty(suiteResult?.assertionContainer)) {
this.updateItemState(run, suiteResult);
}
this.forEachChild((child) => child.updateResultState(run));
}
getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType {
const updateSnapshot = itemCommand === ItemCommand.updateSnapshot;
return {
type: 'by-file-pattern',
updateSnapshot,
testFileNamePattern: this.uri.fsPath,
};
}
getDebugInfo(): ReturnType<Debuggable['getDebugInfo']> {
return { fileName: this.uri.fsPath };
}
public onTestMatched(): void {
this.forEachChild((child) => child.onTestMatched());
}
public gatherSnapshotItems(snapshotItems: SnapshotItemCollection): void {
this.forEachChild((child) => child.gatherSnapshotItems(snapshotItems));
}
}
export class TestData extends TestResultData implements Debuggable {
constructor(
readonly context: JestTestProviderContext,
fileUri: vscode.Uri,
private node: ItemNodeType,
parent: vscode.TestItem,
extraId?: string
) {
super(context, 'TestData');
this.item = this.createTestItem(fileUri, parent, extraId);
this.updateNode(node);
}
private createTestItem(fileUri: vscode.Uri, parent: vscode.TestItem, extraId?: string) {
const item = this.context.createTestItem(
this.makeTestId(fileUri, this.node, extraId),
this.node.name,
fileUri,
this,
parent
);
item.canResolveChildren = false;
return item;
}
getJestRunRequest(itemCommand?: ItemCommand): JestExtRequestType {
return {
type: 'by-file-test-pattern',
updateSnapshot: itemCommand === ItemCommand.updateSnapshot,
testFileNamePattern: this.uri.fsPath,
testNamePattern: this.node.fullName,
};
}
getDebugInfo(): ReturnType<Debuggable['getDebugInfo']> {
return { fileName: this.uri.fsPath, testNamePattern: this.node.fullName };
}
private updateItemRange(): void {
if (this.node.attrs.range) {
const pos = [
this.node.attrs.range.start.line,
this.node.attrs.range.start.column,
this.node.attrs.range.end.line,
this.node.attrs.range.end.column,
];
if (pos.every((n) => n >= 0)) {
this.item.range = new vscode.Range(pos[0], pos[1], pos[2], pos[3]);
return;
}
}
this.item.range = undefined;
}
updateNode(node: ItemNodeType): void {
this.node = node;
this.updateItemRange();
this.syncChildNodes(node);
}
public onTestMatched(): void {
// assertion might have picked up source block location
this.updateItemRange();
this.forEachChild((child) => child.onTestMatched());
}
/**
* determine if a test contains dynamic content, such as template-literal or "test.each" variables from the node info.
* Once the test is run, the node should reflect the resolved names.
*/
isTestNameResolved(): boolean {
//isGroup = true means "test.each"
return !(this.node.attrs.isGroup === 'yes' || this.node.attrs.nonLiteralName === true);
}
public gatherSnapshotItems(snapshotItems: SnapshotItemCollection): void {
// only response if not a "dynamic named" test, which we can't update or view snapshot until the names are resolved
// after running the tests
if (!this.isTestNameResolved()) {
return;
}
if (this.node.attrs.snapshot === 'inline') {
snapshotItems.updatable.push(this.item);
}
if (this.node.attrs.snapshot === 'external') {
snapshotItems.updatable.push(this.item);
snapshotItems.viewable.push(this.item);
}
this.forEachChild((child) => child.gatherSnapshotItems(snapshotItems));
}
public updateResultState(run: JestTestRun): void {
if (this.node && isAssertDataNode(this.node)) {
const assertion = this.node.data;
const errorLine =
assertion.line != null ? this.createLocation(this.uri, assertion.line - 1) : undefined;
this.updateItemState(run, assertion, errorLine);
}
this.forEachChild((child) => child.updateResultState(run));
}
public viewSnapshot(): Promise<void> {
if (this.node.attrs.snapshot === 'external') {
return this.context.ext.testResultProvider.previewSnapshot(
this.uri.fsPath,
this.node.fullName
);
}
this.log('error', `no external snapshot to be viewed: ${this.item.id}`);
return Promise.resolve();
}
}