diff --git a/packages/tracing/src/browser/metrics.ts b/packages/tracing/src/browser/metrics.ts index d7bfd434ba5c..b8b3e51f3467 100644 --- a/packages/tracing/src/browser/metrics.ts +++ b/packages/tracing/src/browser/metrics.ts @@ -23,7 +23,7 @@ export class MetricsInstrumentation { private _clsEntry: LayoutShift | undefined; public constructor() { - if (!isNodeEnv() && global?.performance) { + if (!isNodeEnv() && global?.performance && global?.document) { if (global.performance.mark) { global.performance.mark('sentry-tracing-init'); } diff --git a/packages/tracing/test/browser/metrics.test.ts b/packages/tracing/test/browser/metrics.test.ts index 114a9a480798..429d29131810 100644 --- a/packages/tracing/test/browser/metrics.test.ts +++ b/packages/tracing/test/browser/metrics.test.ts @@ -183,7 +183,25 @@ describe('MetricsInstrumentation', () => { trackers.forEach(tracker => expect(tracker).not.toBeCalled()); }); - it('initializes trackers when not on node and `global.performance` is available.', () => { + it('does not initialize trackers when not on node but `global.document` is not available (in worker)', () => { + // window not necessary for this test, but it is here to exercise that it is absence of document that is checked + addDOMPropertiesToGlobal(['performance', 'addEventListener', 'window']); + const processBackup = global.process; + global.process = undefined; + const documentBackup = global.document; + global.document = undefined; + + const trackers = ['_trackCLS', '_trackLCP', '_trackFID'].map(tracker => + jest.spyOn(MetricsInstrumentation.prototype as any, tracker), + ); + new MetricsInstrumentation(); + global.process = processBackup; + global.document = documentBackup; + + trackers.forEach(tracker => expect(tracker).not.toBeCalled()); + }); + + it('initializes trackers when not on node and `global.performance` and `global.document` are available.', () => { addDOMPropertiesToGlobal(['performance', 'document', 'addEventListener', 'window']); const backup = global.process; global.process = undefined;