Skip to content

Commit

Permalink
fix(browser): Check for existence of instrumentation targets (#8939)
Browse files Browse the repository at this point in the history
There are cases when global objects such as the window object are
shimmed that they define properties such as `document`, but the actual
value is undefined. This exact situation has been occurring and is
causing the instrumentDOM function to throw an error as `'document' in
WINDOW` is technically true though the value is falsey. We should rather
attempt an actual check of the value being truthy rather than if the
property is defined

Co-authored-by: Luca Forstner <[email protected]>
  • Loading branch information
SorsOps and lforst authored Sep 5, 2023
1 parent b57e139 commit ef51993
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
9 changes: 5 additions & 4 deletions packages/utils/src/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,9 @@ export function parseFetchArgs(fetchArgs: unknown[]): { method: string; url: str
}

/** JSDoc */
function instrumentXHR(): void {
if (!('XMLHttpRequest' in WINDOW)) {
export function instrumentXHR(): void {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (!(WINDOW as any).XMLHttpRequest) {
return;
}

Expand Down Expand Up @@ -539,8 +540,8 @@ type InstrumentedElement = Element & {
};

/** JSDoc */
function instrumentDOM(): void {
if (!('document' in WINDOW)) {
export function instrumentDOM(): void {
if (!WINDOW.document) {
return;
}

Expand Down
18 changes: 17 additions & 1 deletion packages/utils/test/instrument.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import { parseFetchArgs } from '../src/instrument';
import { instrumentDOM, instrumentXHR, parseFetchArgs } from '../src/instrument';

jest.mock('../src/worldwide', () => ({
// Return an empty object with undefined properties
getGlobalObject: () => ({
document: undefined,
XMLHttpRequest: undefined,
}),
}));

describe('instrument', () => {
it('instrumentXHR() does not throw if XMLHttpRequest is a key on window but not defined', () => {
expect(instrumentXHR).not.toThrow();
});

it('instrumentDOM() does not throw if XMLHttpRequest is a key on window but not defined', () => {
expect(instrumentDOM).not.toThrow();
});

describe('parseFetchArgs', () => {
it.each([
['string URL only', ['http://example.com'], { method: 'GET', url: 'http://example.com' }],
Expand Down

0 comments on commit ef51993

Please sign in to comment.