-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathjest.js
More file actions
4154 lines (3722 loc) · 145 KB
/
Copy pathjest.js
File metadata and controls
4154 lines (3722 loc) · 145 KB
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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict'
// Capture real timers at module load time, before any test can install fake timers.
const realClearTimeout = clearTimeout
const realSetTimeout = setTimeout
const { readFileSync } = require('node:fs')
const { builtinModules, createRequire } = require('node:module')
const { performance } = require('node:perf_hooks')
const path = require('path')
const satisfies = require('../../../vendor/dist/semifies')
const { DD_MAJOR } = require('../../../version')
const shimmer = require('../../datadog-shimmer')
const { getEnvironmentVariable } = require('../../dd-trace/src/config/helper')
const log = require('../../dd-trace/src/log')
const {
EMPTY_EFD_RETRY_POLICY,
getEfdRetryCountForDuration,
hasEfdRetries,
} = require('../../dd-trace/src/ci-visibility/efd-retry-policy')
const {
getCoveredFilesFromCoverage,
getExecutableFilesFromCoverage,
JEST_WORKER_TRACE_PAYLOAD_CODE,
JEST_WORKER_COVERAGE_PAYLOAD_CODE,
JEST_WORKER_TELEMETRY_PAYLOAD_CODE,
JEST_WORKER_QUARANTINE_PAYLOAD_CODE,
getTestLineStart,
getTestSuitePath,
getTestParametersString,
getIsFaultyEarlyFlakeDetection,
JEST_WORKER_LOGS_PAYLOAD_CODE,
getTestEndLine,
isModifiedTest,
DYNAMIC_NAME_RE,
collectDynamicNamesFromTraces,
recordTestManagementExecution,
recordAttemptToFixExecution,
logAttemptToFixTestExecution,
logTestOptimizationSummary,
TEST_IMPACT_ANALYSIS_ALL_TESTS_SKIPPED_MESSAGE,
getTestCoverageLinesPercentage,
applySkippedCoverageToCoverage,
getTestOptimizationRequestResults,
} = require('../../dd-trace/src/plugins/util/test')
const {
getFormattedJestTestParameters,
getJestTestName,
getRawJestTestName,
getJestSuitesToRun,
removeSeedSuffixFromTestName,
} = require('../../dd-trace/src/plugins/util/jest')
const {
addCoverageBackfillUntestedFiles,
getCoverageBackfillFiles,
} = require('./jest/coverage-backfill')
const {
getChannelPromise,
publishWithCompletion,
} = require('./helpers/channel')
const { addHook, channel } = require('./helpers/instrument')
const testSessionStartCh = channel('ci:jest:session:start')
const testSessionFinishCh = channel('ci:jest:session:finish')
const codeCoverageReportCh = channel('ci:jest:coverage-report')
const testSessionConfigurationCh = channel('ci:jest:session:configuration')
const testSuiteStartCh = channel('ci:jest:test-suite:start')
const testSuiteFinishCh = channel('ci:jest:test-suite:finish')
const testSuiteErrorCh = channel('ci:jest:test-suite:error')
const workerReportTraceCh = channel('ci:jest:worker-report:trace')
const workerReportCoverageCh = channel('ci:jest:worker-report:coverage')
const workerReportLogsCh = channel('ci:jest:worker-report:logs')
const workerReportTelemetryCh = channel('ci:jest:worker-report:telemetry')
const testSuiteCodeCoverageCh = channel('ci:jest:test-suite:code-coverage')
const testStartCh = channel('ci:jest:test:start')
const testSkippedCh = channel('ci:jest:test:skip')
const testFinishCh = channel('ci:jest:test:finish')
const testErrCh = channel('ci:jest:test:err')
const testFnCh = channel('ci:jest:test:fn')
const testSuiteHookFnCh = channel('ci:jest:test-suite:hook:fn')
const skippableSuitesCh = channel('ci:jest:test-suite:skippable')
const libraryConfigurationCh = channel('ci:jest:library-configuration')
const knownTestsCh = channel('ci:jest:known-tests')
const testManagementTestsCh = channel('ci:jest:test-management-tests')
const modifiedFilesCh = channel('ci:jest:modified-files')
const itrSkippedSuitesCh = channel('ci:jest:itr:skipped-suites')
// Message sent by jest's main process to workers to run a test suite (=test file)
// https://github.com/jestjs/jest/blob/1d682f21c7a35da4d3ab3a1436a357b980ebd0fa/packages/jest-worker/src/types.ts#L37
const CHILD_MESSAGE_CALL = 1
// Maximum time we'll wait for the tracer to flush
// The exporter has a 10-second bounded final-flush deadline. Leave enough time
// for its completion callback before Jest's --forceExit fallback takes over.
const FLUSH_TIMEOUT = 12_000
const JEST_SESSION_STATE = Symbol.for('dd-trace:jest:session')
const JEST_BAIL_REPORTER_PATH = require.resolve('./jest/bail-reporter')
const DD_JEST_HANDLE_TEST_EVENT_WRAPPED = Symbol('dd-trace:jest:handle-test-event-wrapped')
const DD_JEST_HANDLE_TEST_EVENT_DATADOG = Symbol('dd-trace:jest:handle-test-event-datadog')
const DD_JEST_CONCURRENT_TEST_ORIGINAL = Symbol('dd-trace:jest:concurrent-test-original')
const isJestWorker = !!getEnvironmentVariable('JEST_WORKER_ID')
const jestSessionState = (globalThis[JEST_SESSION_STATE] ||= {})
// https://github.com/jestjs/jest/blob/41f842a46bb2691f828c3a5f27fc1d6290495b82/packages/jest-circus/src/types.ts#L9C8-L9C54
const RETRY_TIMES = Symbol.for('RETRY_TIMES')
let skippableSuites = []
let skippableSuitesCoverage
let skippedSuitesCoverage = {}
let knownTests = {}
let isCodeCoverageEnabled = false
let isCoverageReportUploadEnabled = false
let isItrEnabled = false
let isSuitesSkippingEnabled = false
let isUserCodeCoverageEnabled = false
let isSuitesSkipped = false
let numSkippedSuites = 0
let hasUnskippableSuites = false
let hasForcedToRunSuites = false
let isEarlyFlakeDetectionEnabled = false
let earlyFlakeDetectionFaultyThreshold = 30
let isEarlyFlakeDetectionFaulty = false
let hasFilteredSkippableSuites = false
let isKnownTestsEnabled = false
let isTestManagementTestsEnabled = false
let testManagementTests = {}
let testManagementAttemptToFixRetries = 0
let isImpactedTestsEnabled = false
let modifiedFiles
let repositoryRoot
let lastCoverageMap
let lastCoverageMapRootDir
let coverageBackfillContexts
let coverageBackfillFiles
let coverageReporterClass
let coverageReporterRequire
let activeTestSuiteAbsolutePath
let isConsoleErrorWrapped = false
const testContexts = new WeakMap()
const originalTestFns = new WeakMap()
const originalHookFns = new WeakMap()
const concurrentHookContextQueues = new WeakMap()
const concurrentHookFns = new WeakMap()
const efdRetryMetadataByTest = new WeakMap()
const removedRetryTests = new WeakSet()
const retriedTestsToNumAttempts = new Map()
const efdTestStatuses = new Map()
const attemptToFixRetriedTestsStatuses = new Map()
const wrappedWorkerChannels = new WeakMap()
// New tests whose names contain likely dynamic data (timestamps, UUIDs, etc.)
// Populated in-process for runInBand, and via worker-report:trace for parallel mode.
const newTestsWithDynamicNames = new Set()
const loggedAttemptToFixTests = new Set()
const testSuiteMockedFiles = new Map()
const testsToBeRetried = new Set()
// Per-test: how many EFD retries were determined after the first execution.
const efdDeterminedRetries = new Map()
// Per-test: total executions to report, including retries Jest ran before the test they belong to.
const efdExpectedExecutions = new Map()
// Tests whose first run exceeded the 5-min threshold — tagged "slow".
const efdSlowAbortedTests = new Set()
// Tests whose first execution determines the duration-based EFD retry count.
const efdCandidates = new Set()
// Tests that are genuinely new (not in known tests list).
const newTests = new Set()
const testSuiteJestObjects = new Map()
const testSuiteDatadogEnvironments = new Map()
const wrappedJestGlobals = new WeakSet()
const wrappedJestObjects = new WeakSet()
const wrappedWorkerInitializers = new WeakSet()
const publishedRuntimeReferenceErrors = new WeakMap()
const wrappedCoverageReporters = new WeakSet()
const coverageReporterRequires = new WeakMap()
const handledJestEvents = new WeakSet()
/**
* @typedef {object} ConcurrentTestOptions
* @property {(...args: unknown[]) => unknown} [concurrentTest]
* @property {unknown} [concurrentTestThisArg]
* @property {EfdRetryGate[]} [efdRetryGates]
* @property {boolean} [isAttemptToFixRetry]
* @property {boolean} [isEfdRetry]
* @property {number} [efdRetryIndex]
* @property {boolean} [isModified]
* @property {(...args: unknown[]) => unknown} [sourceTestFn]
* @property {string} [testParameters]
* @property {number} [timeout]
*/
/**
* @typedef {object} JestRetryOptions
* @property {object} [concurrentTestState]
* @property {EfdRetryGate[]} [efdRetryGates]
* @property {object} jestEvent
* @property {object} state
* @property {boolean} [isModified]
* @property {number} retryCount
* @property {string} retryType
* @property {string} testFullName
*/
/**
* @typedef {object} EfdRetryGate
* @property {Promise<boolean>} promise
* @property {(shouldRun: boolean) => void} resolve
*/
/**
* @typedef {object} DetachedEfdRetry
* @property {object} ctx
* @property {() => void} resolve
* @property {() => void} start
*/
const ATR_RETRY_SUPPRESSION_FLAG = '_ddDisableAtrRetry'
const MINIMUM_JEST_VERSION = DD_MAJOR >= 6 ? '>=28.0.0' : '>=24.8.0'
const MINIMUM_JEST_VERSION_BEFORE_30 = DD_MAJOR >= 6 ? '>=28.0.0 <30.0.0' : '>=24.8.0 <30.0.0'
const MINIMUM_JEST_WORKER_VERSION_BEFORE_30 = DD_MAJOR >= 6 ? '>=28.0.0 <30.0.0' : '>=24.9.0 <30.0.0'
const MINIMUM_JEST_CONFIG_ASYNC_VERSION = DD_MAJOR >= 6 ? '>=28.0.0' : '>=25.1.0'
const MINIMUM_JEST_TEST_SCHEDULER_VERSION = DD_MAJOR >= 6 ? '>=28.0.0' : '>=27.0.0'
const MINIMUM_JEST_COVERAGE_BACKFILL_VERSION = '>=28.0.0'
const atrSuppressedErrors = new Map()
let hasWarnedDeprecatedJestVersion = false
let isJestCoverageBackfillSupported = false
let hasFinishedTestSession = false
let jestEachBind
// Track quarantined tests whose errors were suppressed, keyed by "suite › testName"
const quarantinedFailingTests = new Set()
function getJestRepositoryRoot (readConfigsResult) {
const configuredRepositoryRoot = readConfigsResult.configs
?.find(config => config.testEnvironmentOptions?._ddRepositoryRoot)
?.testEnvironmentOptions._ddRepositoryRoot
return configuredRepositoryRoot || process.cwd()
}
/**
* Sends suppressed quarantine test names from a worker process to the main process.
* Supports both child_process (process.send) and worker_threads (parentPort.postMessage).
* Returns true if the data was sent (worker mode), false if in main process (runInBand).
*
* @param {string[]} testNames
* @returns {boolean}
*/
function sendQuarantineInfoToMainProcess (testNames) {
const payload = [JEST_WORKER_QUARANTINE_PAYLOAD_CODE, JSON.stringify(testNames)]
if (process.send) {
process.send(payload)
return true
}
try {
const { isMainThread, parentPort } = require('node:worker_threads')
if (!isMainThread && parentPort) {
parentPort.postMessage(payload)
return true
}
} catch {
// Not in a worker context
}
return false
}
// based on https://github.com/facebook/jest/blob/main/packages/jest-circus/src/formatNodeAssertErrors.ts#L41
function formatJestError (errors) {
let error
if (Array.isArray(errors)) {
const [originalError, asyncError] = errors
if (originalError === null || !originalError.stack) {
error = asyncError
error.message = originalError
} else {
error = originalError
}
} else {
error = errors
}
return error
}
function warnDeprecatedJestVersion (frameworkVersion) {
if (DD_MAJOR >= 6 || hasWarnedDeprecatedJestVersion || !frameworkVersion ||
!satisfies(frameworkVersion, '<28.0.0')) {
return
}
hasWarnedDeprecatedJestVersion = true
// eslint-disable-next-line no-console
console.warn(
'dd-trace support for Jest<28.0.0 is deprecated and will be removed in dd-trace v6. ' +
'Please upgrade Jest to >=28.0.0.'
)
}
function getTestEnvironmentOptions (config) {
if (config.projectConfig && config.projectConfig.testEnvironmentOptions) { // newer versions
return config.projectConfig.testEnvironmentOptions
}
if (config.testEnvironmentOptions) {
return config.testEnvironmentOptions
}
return {}
}
const MAX_IGNORED_TEST_NAMES = 10
/**
* @typedef {Parameters<typeof logTestOptimizationSummary>[0]} TestOptimizationSummary
*/
function getTestStats (testStatuses) {
return testStatuses.reduce((acc, testStatus) => {
acc[testStatus]++
return acc
}, { pass: 0, fail: 0 })
}
/**
* Formats the ignored-failure section for the Test Optimization summary.
*
* @param {{
* efdNames: string[],
* quarantineNames: string[],
* totalCount: number,
* efdFailureCount: number
* } | undefined} ignoredFailures
* @returns {string}
*/
function formatIgnoredFailuresSummary (ignoredFailures) {
if (!ignoredFailures?.efdFailureCount) return ''
const items = ignoredFailures.efdNames.map(text => ({ text, suffix: 'Early Flake Detection' }))
if (items.length === 0) return ''
const shown = items.slice(0, MAX_IGNORED_TEST_NAMES)
const more = items.length - shown.length
const moreSuffix = more > 0 ? `\n ... and ${more} more` : ''
const formattedItems = shown
.map(({ text, suffix }) => ` • ${text}${suffix ? ` (${suffix})` : ''}`)
.join('\n') + moreSuffix
return `${ignoredFailures.efdFailureCount} test failure(s) were ignored. Exit code set to 0.\n\n${formattedItems}`
}
/**
* Logs a single "Datadog Test Optimization" summary at session end.
*
* @param {{
* efdNames: string[],
* quarantineNames: string[],
* totalCount: number,
* efdFailureCount: number
* } | undefined} ignoredFailures
* @param {NonNullable<TestOptimizationSummary['attemptToFixExecutions']>} attemptToFixExecutions
* @param {boolean} allTestsSkipped
*/
function logSessionSummary (ignoredFailures, attemptToFixExecutions, allTestsSkipped) {
logTestOptimizationSummary({
attemptToFixExecutions,
extraSections: [
formatIgnoredFailuresSummary(ignoredFailures),
allTestsSkipped ? TEST_IMPACT_ANALYSIS_ALL_TESTS_SKIPPED_MESSAGE : '',
],
newTestsWithDynamicNames,
})
loggedAttemptToFixTests.clear()
}
function getTestStatusFromJestResult (status) {
if (status === 'failed') return 'fail'
if (status === 'passed') return 'pass'
}
function getAttemptToFixExecutionsFromJestResults (result) {
const executions = new Map()
const rootDir = result.globalConfig?.rootDir || process.cwd()
for (const { testResults, testFilePath } of result.results.testResults) {
const testSuite = getTestSuitePath(testFilePath, rootDir)
const testManagementTestsForSuite = testManagementTests
?.jest
?.suites
?.[testSuite]
?.tests
if (!testManagementTestsForSuite) continue
for (const { fullName, status } of testResults) {
const testName = removeSeedSuffixFromTestName(fullName)
const testManagementTest = testManagementTestsForSuite[testName]?.properties
if (!testManagementTest?.attempt_to_fix) continue
const testStatus = getTestStatusFromJestResult(status) ||
(status === 'pending' || status === 'todo' ? 'skip' : undefined)
if (!testStatus) continue
recordAttemptToFixExecution(executions, {
testSuite,
testName,
status: testStatus,
isDisabled: testManagementTest.disabled,
isQuarantined: testManagementTest.quarantined,
})
}
}
return executions
}
/**
* Records test-management results reported by Jest after all retries have finished.
*
* @param {{
* globalConfig?: { rootDir?: string },
* results: {
* testResults: Array<{
* testResults: Array<{ fullName: string, status: string }>,
* testFilePath: string
* }>
* }
* }} result
* @param {string[]} quarantineFailureNames
*/
function recordTestManagementExecutionsFromJestResults (result, quarantineFailureNames) {
const rootDir = result.globalConfig?.rootDir || process.cwd()
const failedQuarantinedTests = new Set(quarantineFailureNames)
for (const { testResults, testFilePath } of result.results.testResults) {
const testSuite = getTestSuitePath(testFilePath, rootDir)
const testManagementTestsForSuite = testManagementTests
?.jest
?.suites
?.[testSuite]
?.tests
if (!testManagementTestsForSuite) continue
for (const { fullName, status } of testResults) {
const testName = removeSeedSuffixFromTestName(fullName)
const testManagementTest = testManagementTestsForSuite[testName]?.properties
if (!testManagementTest) continue
const name = `${testSuite} › ${testName}`
recordTestManagementExecution({
testSuite,
testName,
status: failedQuarantinedTests.has(name) ? 'fail' : getTestStatusFromJestResult(status),
isAttemptToFix: testManagementTest.attempt_to_fix,
isDisabled: testManagementTest.disabled,
isQuarantined: testManagementTest.quarantined,
})
}
}
}
function wrapConsoleErrorForJestReferenceErrors () {
if (isConsoleErrorWrapped) return
isConsoleErrorWrapped = true
// eslint-disable-next-line no-console
const originalConsoleError = console.error
// eslint-disable-next-line no-console
console.error = function () {
const [message] = arguments
if (
typeof message === 'string' &&
message.includes('Jest environment has been torn down') &&
activeTestSuiteAbsolutePath
) {
publishRuntimeReferenceError({ _testPath: activeTestSuiteAbsolutePath }, message)
}
return originalConsoleError.apply(this, arguments)
}
}
function isDatadogJestEventHandled (event) {
return event && typeof event === 'object' && handledJestEvents.has(event)
}
function markDatadogJestEventHandled (event) {
if (event && typeof event === 'object') {
handledJestEvents.add(event)
}
}
/**
* Gets the original Jest concurrent registration function behind a Datadog wrapper.
*
* @param {(...args: unknown[]) => unknown} concurrentTest
* @returns {(...args: unknown[]) => unknown}
*/
function getOriginalConcurrentTest (concurrentTest) {
return concurrentTest[DD_JEST_CONCURRENT_TEST_ORIGINAL] || concurrentTest
}
/**
* Marks a Datadog concurrent registration wrapper with its original Jest function.
*
* @param {(...args: unknown[]) => unknown} wrappedConcurrentTest
* @param {(...args: unknown[]) => unknown} originalConcurrentTest
* @returns {void}
*/
function setOriginalConcurrentTest (wrappedConcurrentTest, originalConcurrentTest) {
Object.defineProperty(wrappedConcurrentTest, DD_JEST_CONCURRENT_TEST_ORIGINAL, {
configurable: true,
value: originalConcurrentTest,
})
}
/**
* Wraps a custom Jest environment handler so Datadog still observes events even
* when the custom environment does not call `super.handleTestEvent`.
*
* @param {(event: object, state: object) => Promise<void>|void} handleTestEvent
* @param {(event: object, state: object) => Promise<void>|void} datadogHandleTestEvent
* @returns {(event: object, state: object) => Promise<void>|void}
*/
function getWrappedCustomHandleTestEvent (handleTestEvent, datadogHandleTestEvent) {
if (
!handleTestEvent ||
handleTestEvent === datadogHandleTestEvent ||
handleTestEvent[DD_JEST_HANDLE_TEST_EVENT_WRAPPED]
) {
return handleTestEvent || datadogHandleTestEvent
}
const wrappedHandleTestEvent = function (event, state) {
const result = handleTestEvent.call(this, event, state)
const runDatadogHandler = value => {
if (isDatadogJestEventHandled(event)) return value
const datadogResult = datadogHandleTestEvent.call(this, event, state)
if (typeof datadogResult?.then === 'function') {
return datadogResult.then(() => value)
}
return value
}
if (event.name === 'add_test') {
runDatadogHandler(result)
return result
}
if (typeof result?.then === 'function') {
return result.then(runDatadogHandler)
}
return runDatadogHandler(result)
}
wrappedHandleTestEvent[DD_JEST_HANDLE_TEST_EVENT_WRAPPED] = true
return wrappedHandleTestEvent
}
/**
* Mirrors the test selection checks Jest Circus performs after publishing `test_start`.
*
* @param {object} test
* @param {boolean} hasFocusedTests
* @param {RegExp|undefined} testNamePattern
* @returns {boolean}
*/
function isJestTestSkipped (test, hasFocusedTests, testNamePattern) {
if (
test.mode === 'skip' ||
(hasFocusedTests && test.mode !== 'only') ||
(testNamePattern && !testNamePattern.test(getRawJestTestName(test)))
) {
return true
}
let parent = test.parent
while (parent) {
if (parent.mode === 'skip') return true
parent = parent.parent
}
return false
}
function getWrappedEnvironment (BaseEnvironment, jestVersion) {
const hasConcurrentTestsStartEvent = satisfies(jestVersion, '>=30.0.0')
const hasTestsInChildren = satisfies(jestVersion, '>=26.0.0')
/**
* @param {object} describeBlock
* @returns {object[]|undefined}
*/
function getTestEntries (describeBlock) {
return hasTestsInChildren ? describeBlock?.children : describeBlock?.tests
}
return class DatadogEnvironment extends BaseEnvironment {
#activeDetachedEfdRetries
#detachedEfdRetryConcurrency
#detachedEfdRetryQueue
#discardedEfdRetryTests
#earlyFlakeDetectionRetryPolicy
#efdRetryGatesByName
#pendingPre30ConcurrentTests
constructor (config, context) {
super(config, context)
const rootDir = config.globalConfig ? config.globalConfig.rootDir : config.rootDir
this.rootDir = rootDir
this.nameToParams = {}
this.global._ddtrace = global._ddtrace
this.hasSnapshotTests = undefined
this.testSuiteAbsolutePath = context.testPath
activeTestSuiteAbsolutePath = this.testSuiteAbsolutePath
testSuiteDatadogEnvironments.set(this.testSuiteAbsolutePath, this)
wrapConsoleErrorForJestReferenceErrors()
this.globalConfig = config.globalConfig
this.displayName = config.projectConfig?.displayName?.name || config.displayName
this.testEnvironmentOptions = getTestEnvironmentOptions(config)
const repositoryRoot = this.testEnvironmentOptions._ddRepositoryRoot
this.testSuite = getTestSuitePath(context.testPath, rootDir)
// TODO: could we grab testPath from `this.getVmContext().expect.getState()` instead?
// so we don't rely on context being passed (some custom test environment do not pass it)
if (repositoryRoot) {
this.testSourceFile = getTestSuitePath(context.testPath, repositoryRoot)
this.repositoryRoot = repositoryRoot
}
this.isEarlyFlakeDetectionEnabled = this.testEnvironmentOptions._ddIsEarlyFlakeDetectionEnabled
this.isFlakyTestRetriesEnabled = this.testEnvironmentOptions._ddIsFlakyTestRetriesEnabled
this.flakyTestRetriesCount = this.testEnvironmentOptions._ddFlakyTestRetriesCount
this.isDiEnabled = this.testEnvironmentOptions._ddIsDiEnabled
this.isKnownTestsEnabled = this.testEnvironmentOptions._ddIsKnownTestsEnabled
this.isTestManagementTestsEnabled = this.testEnvironmentOptions._ddIsTestManagementTestsEnabled
this.isImpactedTestsEnabled = this.testEnvironmentOptions._ddIsImpactedTestsEnabled
this.hasConcurrentTests = false
this.concurrentTestContexts = new Map()
this.concurrentTestStates = new WeakMap()
this.concurrentTestSourceFns = new WeakMap()
this.testParametersByFunction = new WeakMap()
this.wrappedConcurrentTestFunctions = new WeakSet()
this.jestEachBind = undefined
this.#activeDetachedEfdRetries = 0
this.#detachedEfdRetryConcurrency = 1
this.#pendingPre30ConcurrentTests = 0
this.#earlyFlakeDetectionRetryPolicy =
this.testEnvironmentOptions._ddEarlyFlakeDetectionRetryPolicy ?? EMPTY_EFD_RETRY_POLICY
if (this.isKnownTestsEnabled) {
try {
this.knownTestsForThisSuite = this.getKnownTestsForSuite(this.testEnvironmentOptions._ddKnownTests)
if (!Array.isArray(this.knownTestsForThisSuite)) {
log.warn('this.knownTestsForThisSuite is not an array so new test and Early Flake detection is disabled.')
this.isEarlyFlakeDetectionEnabled = false
this.isKnownTestsEnabled = false
}
} catch {
// If there has been an error parsing the tests, we'll disable Early Flake Deteciton
this.isEarlyFlakeDetectionEnabled = false
this.isKnownTestsEnabled = false
}
}
if (this.isFlakyTestRetriesEnabled) {
const currentNumRetries = this.global[RETRY_TIMES]
if (!currentNumRetries) {
this.global[RETRY_TIMES] = this.flakyTestRetriesCount
}
}
if (this.isTestManagementTestsEnabled) {
try {
const hasTestManagementTests = !!testManagementTests?.jest
testManagementAttemptToFixRetries = this.testEnvironmentOptions._ddTestManagementAttemptToFixRetries
this.testManagementTestsForThisSuite = hasTestManagementTests
? this.getTestManagementTestsForSuite(testManagementTests?.jest?.suites?.[this.testSuite]?.tests)
: this.getTestManagementTestsForSuite(this.testEnvironmentOptions._ddTestManagementTests)
} catch (e) {
log.error('Error parsing test management tests', e)
this.isTestManagementTestsEnabled = false
}
}
if (this.isImpactedTestsEnabled) {
try {
this.modifiedFiles = modifiedFiles ?? this.testEnvironmentOptions._ddModifiedFiles
} catch (e) {
log.error('Error parsing impacted tests', e)
this.isImpactedTestsEnabled = false
}
}
this[DD_JEST_HANDLE_TEST_EVENT_DATADOG] = DatadogEnvironment.prototype.handleTestEvent
this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
}
/**
* Rechecks custom `handleTestEvent` implementations after subclass instance fields
* and constructors have run.
*
* @returns {Promise<void>|void}
*/
setup () {
this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
if (super.setup) {
const result = super.setup()
if (typeof result?.then === 'function') {
return result.then(() => {
this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
})
}
this.wrapCustomHandleTestEvent(DatadogEnvironment.prototype.handleTestEvent)
return result
}
}
/**
* Rebuilds serial `test.each` so every generated row function keeps its parameters.
*
* @param {Function|undefined} test
* @returns {void}
*/
bindTestEach (test) {
if (typeof test?.each !== 'function') return
const bind = this.getJestEachBind()
if (typeof bind !== 'function') {
const environment = this
shimmer.wrap(test, 'each', each => function (...args) {
const testParameters = getFormattedJestTestParameters(args)
const eachBind = each.apply(this, args)
return function (...args) {
const [testName] = args
environment.setNameToParams(testName, testParameters)
return eachBind.apply(this, args)
}
})
return
}
// Jest creates each row function at runtime, so Orchestrion cannot associate parameters statically.
const environment = this
test.each = function wrappedTestEach (...eachArgs) {
const testParameters = getFormattedJestTestParameters(eachArgs)
return function (...testArgs) {
let parameterIndex = 0
const eachTest = function (testName, testFn, ...callArgs) {
const parameters = testParameters?.[parameterIndex++]
if (parameters !== undefined && typeof testFn === 'function') {
environment.appendNameToParams(testName, parameters)
environment.testParametersByFunction.set(
testFn,
getTestParametersString(environment.nameToParams, testName)
)
}
return test.call(this, testName, testFn, ...callArgs)
}
const eachBind = bind(eachTest).apply(this, eachArgs)
return eachBind.apply(this, testArgs)
}
}
}
/**
* Wraps Jest's concurrent test registration methods so eager concurrent bodies
* in older Jest versions execute inside their test span context.
*
* @param {object} state
* @returns {void}
*/
wrapConcurrentTest (state) {
this.concurrentTestState = state
this.wrapConcurrentTestGlobals(this.global.test, state)
}
/**
* Wraps one Jest `test` function object's concurrent registration methods.
*
* @param {Function|undefined} test
* @param {object} state
* @returns {void}
*/
wrapConcurrentTestGlobals (test, state) {
if (!state) return
const concurrentTest = test?.concurrent
if (typeof concurrentTest !== 'function') return
this.wrapConcurrentTestFunction(test, 'concurrent', state)
this.wrapConcurrentTestFunction(test.concurrent, 'only', state)
this.wrapConcurrentTestFunction(test.concurrent, 'failing', state)
this.wrapConcurrentTestFunction(test.concurrent.only, 'failing', state)
}
/**
* Wraps one concurrent test function variant.
*
* @param {object} target
* @param {string} methodName
* @param {object} state
* @returns {void}
*/
wrapConcurrentTestFunction (target, methodName, state) {
let concurrentTest = target?.[methodName]
if (typeof concurrentTest !== 'function') return
if (this.wrappedConcurrentTestFunctions.has(concurrentTest)) return
const originalConcurrentTest = getOriginalConcurrentTest(concurrentTest)
if (originalConcurrentTest !== concurrentTest) {
target[methodName] = originalConcurrentTest
concurrentTest = originalConcurrentTest
}
if (typeof concurrentTest !== 'function') return
const environment = this
shimmer.wrap(target, methodName, concurrentTest => {
return function wrappedConcurrentTest (testName, testFn, ...args) {
if (typeof testFn !== 'function') {
return concurrentTest.apply(this, arguments)
}
environment.hasConcurrentTests = true
const asyncError = environment.isImpactedTestsEnabled
? new Error('Datadog concurrent test registration')
: undefined
const wrappedTestFn = environment.createConcurrentTestFn(testName, testFn, asyncError, state, {
concurrentTest,
concurrentTestThisArg: this,
sourceTestFn: environment.concurrentTestSourceFns.get(testFn),
timeout: args[0],
})
return concurrentTest.call(this, testName, wrappedTestFn, ...args)
}
})
const wrappedConcurrentTest = target[methodName]
setOriginalConcurrentTest(wrappedConcurrentTest, concurrentTest)
this.wrappedConcurrentTestFunctions.add(wrappedConcurrentTest)
this.bindConcurrentEach(wrappedConcurrentTest, methodName === 'failing')
}
/**
* Rebuilds a concurrent `.each` helper so each generated row calls the wrapped test function.
*
* @param {Function} concurrentTest
* @param {boolean} needsEachError
* @returns {void}
*/
bindConcurrentEach (concurrentTest, needsEachError) {
if (typeof concurrentTest?.each !== 'function') return
const bind = this.getJestEachBind()
if (typeof bind !== 'function') return
const environment = this
concurrentTest.each = function wrappedConcurrentEach (...eachArgs) {
const testParameters = getFormattedJestTestParameters(eachArgs)
return function (...testArgs) {
let parameterIndex = 0
const sourceTestFn = testArgs[1]
const concurrentEachTest = function (testName, testFn, ...callArgs) {
const parameters = testParameters?.[parameterIndex++]
if (parameters !== undefined) {
environment.appendNameToParams(testName, parameters)
}
if (typeof testFn === 'function' && typeof sourceTestFn === 'function') {
environment.concurrentTestSourceFns.set(testFn, sourceTestFn)
}
return concurrentTest.call(this, testName, testFn, ...callArgs)
}
const eachBind = bind(concurrentEachTest, false, needsEachError).apply(this, eachArgs)
return eachBind.apply(this, testArgs)
}
}
}
/**
* Creates a Jest test function wrapper and stores its concurrent execution state.
*
* @param {string} testName
* @param {(...args: unknown[]) => unknown} testFn
* @param {Error|undefined} asyncError
* @param {object} state
* @param {ConcurrentTestOptions|undefined} options
* @returns {(...args: unknown[]) => unknown}
*/
createConcurrentTestFn (testName, testFn, asyncError, state, options) {
const concurrentTestState = {
concurrentTest: options?.concurrentTest,
concurrentTestThisArg: options?.concurrentTestThisArg,
ctx: this.createConcurrentTestContext(testName, testFn, asyncError, state, options),
numExecutions: 0,
state,
testFn,
}
concurrentTestState.ctx.concurrentTestState = concurrentTestState
const environment = this
const wrappedTestFn = shimmer.wrapFunction(testFn, testFn => function (...args) {
return environment.runConcurrentTestFn(concurrentTestState, testFn, this, args)
})
this.concurrentTestStates.set(wrappedTestFn, concurrentTestState)
return wrappedTestFn
}
/**
* Gets Jest's table-driven test binder from the user's Jest installation.
*
* @returns {Function|undefined}
*/
getJestEachBind () {
if (this.jestEachBind !== undefined) return this.jestEachBind
if (typeof jestEachBind === 'function') {
this.jestEachBind = jestEachBind
return this.jestEachBind
}
let jestEach
try {
jestEach = createRequire(path.join(this.rootDir, 'package.json'))('jest-each')
} catch {
try {
jestEach = createRequire(path.join(process.cwd(), 'package.json'))('jest-each')
} catch {
jestEach = undefined
}
}
this.jestEachBind = jestEach?.bind
return this.jestEachBind
}
/**
* Creates the context used to start and finish a concurrent test span.
*
* @param {string} testName
* @param {(...args: unknown[]) => unknown} testFn
* @param {Error|undefined} asyncError
* @param {object} state
* @param {ConcurrentTestOptions|undefined} options
* @returns {object}
*/
createConcurrentTestContext (testName, testFn, asyncError, state, options) {
const testFullName = this.getTestNameFromAddTestEvent({ testName }, state)
const isNewTest = this.isKnownTestsEnabled && !this.knownTestsForThisSuite?.includes(testFullName)
const isAttemptToFix = this.isTestManagementTestsEnabled &&
this.testManagementTestsForThisSuite?.attemptToFix?.includes(testFullName)
const sourceTestFn = options?.sourceTestFn || testFn
const ctx = {
name: testFullName,
suite: this.testSuite,
testSourceFile: this.testSourceFile,
displayName: this.displayName,
testParameters: options?.testParameters || getTestParametersString(this.nameToParams, testName),
frameworkVersion: jestVersion,
isNew: isNewTest,
isEfdRetry: options?.isEfdRetry === true,
efdRetryGates: options?.efdRetryGates,
efdRetryIndex: options?.efdRetryIndex,
isAttemptToFix,
isAttemptToFixRetry: options?.isAttemptToFixRetry === true,
isJestRetry: false,
isDisabled: this.testManagementTestsForThisSuite?.disabled?.includes(testFullName),
isQuarantined: this.testManagementTestsForThisSuite?.quarantined?.includes(testFullName),
isModified: options?.isModified ?? this.isTestModified(asyncError, sourceTestFn),
hasDynamicName: isNewTest && DYNAMIC_NAME_RE.test(testFullName),
testSuiteAbsolutePath: this.testSuiteAbsolutePath,
testTimeout: options?.timeout || state.testTimeout,
}
let contexts = this.concurrentTestContexts.get(testFullName)
if (contexts) {
contexts.push(ctx)
} else {
contexts = [ctx]
this.concurrentTestContexts.set(testFullName, contexts)
}
return ctx
}
/**
* Checks if a test overlaps modified lines for impacted-test detection.
*
* @param {Error|undefined} asyncError
* @param {Function|undefined} testFn
* @returns {boolean}
*/
isTestModified (asyncError, testFn) {
if (!this.isImpactedTestsEnabled || !asyncError || typeof testFn !== 'function') return false
const testStartLine = getTestLineStart(asyncError, this.testSuite)
const testEndLine = getTestEndLine(testFn, testStartLine)
return isModifiedTest(
this.testSourceFile,