Skip to content

Commit

Permalink
fix(tracing): Prevent metrics erroring module load in web workers (#3941
Browse files Browse the repository at this point in the history
)

Minimal fix for #3934
  • Loading branch information
gthb authored Aug 31, 2021
1 parent 949f1b6 commit fdee17e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/tracing/src/browser/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Expand Down
20 changes: 19 additions & 1 deletion packages/tracing/test/browser/metrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit fdee17e

Please sign in to comment.