forked from getsentry/sentry-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbrowsertracing.test.ts
546 lines (461 loc) · 20.8 KB
/
browsertracing.test.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
import { BrowserClient } from '@sentry/browser';
import { Hub, makeMain } from '@sentry/core';
import type { BaseTransportOptions, ClientOptions, DsnComponents } from '@sentry/types';
import { InstrumentHandlerCallback, InstrumentHandlerType, WINDOW } from '@sentry/utils';
import { JSDOM } from 'jsdom';
import { BrowserTracing, BrowserTracingOptions, getMetaContent } from '../../src/browser/browsertracing';
import { defaultRequestInstrumentationOptions } from '../../src/browser/request';
import { instrumentRoutingWithDefaults } from '../../src/browser/router';
import * as hubExtensions from '../../src/hubextensions';
import {
DEFAULT_FINAL_TIMEOUT,
DEFAULT_HEARTBEAT_INTERVAL,
DEFAULT_IDLE_TIMEOUT,
IdleTransaction,
} from '../../src/idletransaction';
import { getActiveTransaction } from '../../src/utils';
import { getDefaultBrowserClientOptions } from '../testutils';
let mockChangeHistory: ({ to, from }: { to: string; from?: string }) => void = () => undefined;
jest.mock('@sentry/utils', () => {
const actual = jest.requireActual('@sentry/utils');
return {
...actual,
addInstrumentationHandler: (type: InstrumentHandlerType, callback: InstrumentHandlerCallback): void => {
if (type === 'history') {
// rather than actually add the navigation-change handler, grab a reference to it, so we can trigger it manually
mockChangeHistory = callback;
}
},
};
});
jest.mock('../../src/browser/metrics');
const { logger } = jest.requireActual('@sentry/utils');
const warnSpy = jest.spyOn(logger, 'warn');
beforeAll(() => {
const dom = new JSDOM();
// @ts-ignore need to override global document
WINDOW.document = dom.window.document;
// @ts-ignore need to override global document
WINDOW.window = dom.window;
// @ts-ignore need to override global document
WINDOW.location = dom.window.location;
});
describe('BrowserTracing', () => {
let hub: Hub;
beforeEach(() => {
jest.useFakeTimers();
const options = getDefaultBrowserClientOptions({ tracesSampleRate: 1 });
hub = new Hub(new BrowserClient(options));
makeMain(hub);
document.head.innerHTML = '';
warnSpy.mockClear();
});
afterEach(() => {
const activeTransaction = getActiveTransaction();
if (activeTransaction) {
// Should unset off of scope.
activeTransaction.finish();
}
});
function createBrowserTracing(setup?: boolean, _options?: Partial<BrowserTracingOptions>): BrowserTracing {
const instance = new BrowserTracing(_options);
if (setup) {
const processor = () => undefined;
instance.setupOnce(processor, () => hub);
}
return instance;
}
// These are important enough to check with a test as incorrect defaults could
// break a lot of users' configurations.
it('is created with default settings', () => {
const browserTracing = createBrowserTracing();
expect(browserTracing.options).toEqual({
_experiments: {
enableLongTask: true,
},
idleTimeout: DEFAULT_IDLE_TIMEOUT,
finalTimeout: DEFAULT_FINAL_TIMEOUT,
heartbeatInterval: DEFAULT_HEARTBEAT_INTERVAL,
markBackgroundTransactions: true,
routingInstrumentation: instrumentRoutingWithDefaults,
startTransactionOnLocationChange: true,
startTransactionOnPageLoad: true,
...defaultRequestInstrumentationOptions,
});
});
/**
* All of these tests under `describe('route transaction')` are tested with
* `browserTracing.options = { routingInstrumentation: customInstrumentRouting }`,
* so that we can show this functionality works independent of the default routing integration.
*/
describe('route transaction', () => {
const customInstrumentRouting = (customStartTransaction: (obj: any) => void) => {
customStartTransaction({ name: 'a/path', op: 'pageload' });
};
it('calls custom routing instrumenation', () => {
createBrowserTracing(true, {
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).toBeDefined();
expect(transaction.name).toBe('a/path');
expect(transaction.op).toBe('pageload');
});
it('trims all transactions', () => {
createBrowserTracing(true, {
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
const span = transaction.startChild();
span.finish();
if (span.endTimestamp) {
transaction.finish(span.endTimestamp + 12345);
}
expect(transaction.endTimestamp).toBe(span.endTimestamp);
});
describe('tracingOrigins', () => {
it('warns and uses default tracing origins if none are provided', () => {
const inst = createBrowserTracing(true, {
routingInstrumentation: customInstrumentRouting,
});
expect(warnSpy).toHaveBeenCalledTimes(2);
expect(inst.options.tracingOrigins).toEqual(defaultRequestInstrumentationOptions.tracingOrigins);
});
it('warns and uses default tracing origins if tracing origins are not defined', () => {
const inst = createBrowserTracing(true, {
routingInstrumentation: customInstrumentRouting,
tracingOrigins: undefined,
});
expect(warnSpy).toHaveBeenCalledTimes(2);
expect(inst.options.tracingOrigins).toEqual(defaultRequestInstrumentationOptions.tracingOrigins);
});
it('sets tracing origins if provided and does not warn', () => {
const sampleTracingOrigins = ['something'];
const inst = createBrowserTracing(true, {
routingInstrumentation: customInstrumentRouting,
tracingOrigins: sampleTracingOrigins,
});
expect(warnSpy).toHaveBeenCalledTimes(0);
expect(inst.options.tracingOrigins).toEqual(sampleTracingOrigins);
});
it('sets tracing origins to an empty array and does not warn', () => {
const sampleTracingOrigins: string[] = [];
const inst = createBrowserTracing(true, {
routingInstrumentation: customInstrumentRouting,
tracingOrigins: sampleTracingOrigins,
});
expect(warnSpy).toHaveBeenCalledTimes(0);
expect(inst.options.tracingOrigins).toEqual(sampleTracingOrigins);
});
});
describe('beforeNavigate', () => {
it('is called on transaction creation', () => {
const mockBeforeNavigation = jest.fn().mockReturnValue({ name: 'here/is/my/path' });
createBrowserTracing(true, {
beforeNavigate: mockBeforeNavigation,
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).toBeDefined();
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
});
it('creates a transaction with sampled = false if beforeNavigate returns undefined', () => {
const mockBeforeNavigation = jest.fn().mockReturnValue(undefined);
createBrowserTracing(true, {
beforeNavigate: mockBeforeNavigation,
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction.sampled).toBe(false);
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
});
it('can override default context values', () => {
const mockBeforeNavigation = jest.fn(ctx => ({
...ctx,
op: 'not-pageload',
}));
createBrowserTracing(true, {
beforeNavigate: mockBeforeNavigation,
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).toBeDefined();
expect(transaction.op).toBe('not-pageload');
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
});
it("sets transaction name source to `'custom'` if name is changed", () => {
const mockBeforeNavigation = jest.fn(ctx => ({
...ctx,
name: 'newName',
}));
createBrowserTracing(true, {
beforeNavigate: mockBeforeNavigation,
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).toBeDefined();
expect(transaction.name).toBe('newName');
expect(transaction.metadata.source).toBe('custom');
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
});
it('sets transaction name source to default `custom` if name is not changed', () => {
const mockBeforeNavigation = jest.fn(ctx => ({
...ctx,
}));
createBrowserTracing(true, {
beforeNavigate: mockBeforeNavigation,
routingInstrumentation: customInstrumentRouting,
});
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).toBeDefined();
expect(transaction.name).toBe('a/path');
expect(transaction.metadata.source).toBe('custom');
expect(mockBeforeNavigation).toHaveBeenCalledTimes(1);
});
});
it('sets transaction context from sentry-trace header', () => {
const name = 'sentry-trace';
const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1';
document.head.innerHTML =
`<meta name="${name}" content="${content}">` + '<meta name="baggage" content="sentry-release=2.1.14,foo=bar">';
const startIdleTransaction = jest.spyOn(hubExtensions, 'startIdleTransaction');
createBrowserTracing(true, { routingInstrumentation: customInstrumentRouting });
expect(startIdleTransaction).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({
traceId: '126de09502ae4e0fb26c6967190756a4',
parentSpanId: 'b6e54397b12a2a0f',
parentSampled: true,
metadata: {
dynamicSamplingContext: { release: '2.1.14' },
},
}),
expect.any(Number),
expect.any(Number),
expect.any(Boolean),
expect.any(Object),
expect.any(Number),
);
});
describe('idleTimeout', () => {
it('is created by default', () => {
createBrowserTracing(true, { routingInstrumentation: customInstrumentRouting });
const mockFinish = jest.fn();
const transaction = getActiveTransaction(hub) as IdleTransaction;
transaction.finish = mockFinish;
const span = transaction.startChild(); // activities = 1
span.finish(); // activities = 0
expect(mockFinish).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT);
expect(mockFinish).toHaveBeenCalledTimes(1);
});
it('can be a custom value', () => {
createBrowserTracing(true, { idleTimeout: 2000, routingInstrumentation: customInstrumentRouting });
const mockFinish = jest.fn();
const transaction = getActiveTransaction(hub) as IdleTransaction;
transaction.finish = mockFinish;
const span = transaction.startChild(); // activities = 1
span.finish(); // activities = 0
expect(mockFinish).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(2000);
expect(mockFinish).toHaveBeenCalledTimes(1);
});
});
describe('heartbeatInterval', () => {
it('can be a custom value', () => {
const interval = 200;
createBrowserTracing(true, { heartbeatInterval: interval, routingInstrumentation: customInstrumentRouting });
const mockFinish = jest.fn();
const transaction = getActiveTransaction(hub) as IdleTransaction;
transaction.finish = mockFinish;
const span = transaction.startChild(); // activities = 1
span.finish(); // activities = 0
expect(mockFinish).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(interval * 3);
expect(mockFinish).toHaveBeenCalledTimes(1);
});
});
});
// Integration tests for the default routing instrumentation
describe('default routing instrumentation', () => {
describe('pageload transaction', () => {
it('is created on setup on scope', () => {
createBrowserTracing(true);
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).toBeDefined();
expect(transaction.op).toBe('pageload');
});
it('is not created if the option is false', () => {
createBrowserTracing(true, { startTransactionOnPageLoad: false });
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).not.toBeDefined();
});
});
describe('navigation transaction', () => {
beforeEach(() => {
mockChangeHistory = () => undefined;
});
it('it is not created automatically at startup', () => {
createBrowserTracing(true);
jest.runAllTimers();
const transaction = getActiveTransaction(hub) as IdleTransaction;
expect(transaction).not.toBeDefined();
});
it('is created on location change', () => {
createBrowserTracing(true);
const transaction1 = getActiveTransaction(hub) as IdleTransaction;
expect(transaction1.op).toBe('pageload');
expect(transaction1.endTimestamp).not.toBeDefined();
mockChangeHistory({ to: 'here', from: 'there' });
const transaction2 = getActiveTransaction(hub) as IdleTransaction;
expect(transaction2.op).toBe('navigation');
expect(transaction1.endTimestamp).toBeDefined();
});
it('is not created if startTransactionOnLocationChange is false', () => {
createBrowserTracing(true, { startTransactionOnLocationChange: false });
const transaction1 = getActiveTransaction(hub) as IdleTransaction;
expect(transaction1.op).toBe('pageload');
expect(transaction1.endTimestamp).not.toBeDefined();
mockChangeHistory({ to: 'here', from: 'there' });
const transaction2 = getActiveTransaction(hub) as IdleTransaction;
expect(transaction2.op).toBe('pageload');
});
});
});
describe('sentry-trace and baggage <meta> elements', () => {
describe('getMetaContent', () => {
it('finds the specified tag and extracts the value', () => {
const name = 'sentry-trace';
const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1';
document.head.innerHTML = `<meta name="${name}" content="${content}">`;
const metaTagValue = getMetaContent(name);
expect(metaTagValue).toBe(content);
});
it("doesn't return meta tags other than the one specified", () => {
document.head.innerHTML = '<meta name="cat-cafe">';
const metaTagValue = getMetaContent('dogpark');
expect(metaTagValue).toBe(null);
});
it('can pick the correct tag out of multiple options', () => {
const name = 'sentry-trace';
const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1';
const sentryTraceMeta = `<meta name="${name}" content="${content}">`;
const otherMeta = '<meta name="cat-cafe">';
document.head.innerHTML = `${sentryTraceMeta} ${otherMeta}`;
const metaTagValue = getMetaContent(name);
expect(metaTagValue).toBe(content);
});
});
describe('using the <meta> tag data', () => {
beforeEach(() => {
hub.getClient()!.getOptions = () => {
return {
release: '1.0.0',
environment: 'production',
} as ClientOptions<BaseTransportOptions>;
};
hub.getClient()!.getDsn = () => {
return {
publicKey: 'pubKey',
} as DsnComponents;
};
});
it('uses the tracing data for pageload transactions', () => {
// make sampled false here, so we can see that it's being used rather than the tracesSampleRate-dictated one
document.head.innerHTML =
'<meta name="sentry-trace" content="12312012123120121231201212312012-1121201211212012-0">' +
'<meta name="baggage" content="sentry-release=2.1.14,foo=bar">';
// pageload transactions are created as part of the BrowserTracing integration's initialization
createBrowserTracing(true);
const transaction = getActiveTransaction(hub) as IdleTransaction;
const dynamicSamplingContext = transaction.getDynamicSamplingContext()!;
expect(transaction).toBeDefined();
expect(transaction.op).toBe('pageload');
expect(transaction.traceId).toEqual('12312012123120121231201212312012');
expect(transaction.parentSpanId).toEqual('1121201211212012');
expect(transaction.sampled).toBe(false);
expect(dynamicSamplingContext).toBeDefined();
expect(dynamicSamplingContext).toStrictEqual({ release: '2.1.14' });
});
it('puts frozen Dynamic Sampling Context on pageload transactions if sentry-trace data and only 3rd party baggage is present', () => {
// make sampled false here, so we can see that it's being used rather than the tracesSampleRate-dictated one
document.head.innerHTML =
'<meta name="sentry-trace" content="12312012123120121231201212312012-1121201211212012-0">' +
'<meta name="baggage" content="foo=bar">';
// pageload transactions are created as part of the BrowserTracing integration's initialization
createBrowserTracing(true);
const transaction = getActiveTransaction(hub) as IdleTransaction;
const dynamicSamplingContext = transaction.getDynamicSamplingContext()!;
expect(transaction).toBeDefined();
expect(transaction.op).toBe('pageload');
expect(transaction.traceId).toEqual('12312012123120121231201212312012');
expect(transaction.parentSpanId).toEqual('1121201211212012');
expect(transaction.sampled).toBe(false);
expect(dynamicSamplingContext).toStrictEqual({});
});
it('ignores the meta tag data for navigation transactions', () => {
mockChangeHistory = () => undefined;
document.head.innerHTML =
'<meta name="sentry-trace" content="12312012123120121231201212312012-1121201211212012-0">' +
'<meta name="baggage" content="sentry-release=2.1.14">';
createBrowserTracing(true);
mockChangeHistory({ to: 'here', from: 'there' });
const transaction = getActiveTransaction(hub) as IdleTransaction;
const dynamicSamplingContext = transaction.getDynamicSamplingContext()!;
expect(transaction).toBeDefined();
expect(transaction.op).toBe('navigation');
expect(transaction.traceId).not.toEqual('12312012123120121231201212312012');
expect(transaction.parentSpanId).toBeUndefined();
expect(dynamicSamplingContext).toStrictEqual({
release: '1.0.0',
environment: 'production',
public_key: 'pubKey',
trace_id: expect.not.stringMatching('12312012123120121231201212312012'),
});
});
});
});
describe('sampling', () => {
const dogParkLocation = {
hash: '#next-to-the-fountain',
host: 'the.dog.park',
hostname: 'the.dog.park',
href: 'mutualsniffing://the.dog.park/by/the/trees/?chase=me&please=thankyou#next-to-the-fountain',
origin: "'mutualsniffing://the.dog.park",
pathname: '/by/the/trees/',
port: '',
protocol: 'mutualsniffing:',
search: '?chase=me&please=thankyou',
};
it('extracts window.location/self.location for sampling context in pageload transactions', () => {
WINDOW.location = dogParkLocation as any;
const tracesSampler = jest.fn();
const options = getDefaultBrowserClientOptions({ tracesSampler });
hub.bindClient(new BrowserClient(options));
// setting up the BrowserTracing integration automatically starts a pageload transaction
createBrowserTracing(true);
expect(tracesSampler).toHaveBeenCalledWith(
expect.objectContaining({
location: dogParkLocation,
transactionContext: expect.objectContaining({ op: 'pageload' }),
}),
);
});
it('extracts window.location/self.location for sampling context in navigation transactions', () => {
WINDOW.location = dogParkLocation as any;
const tracesSampler = jest.fn();
const options = getDefaultBrowserClientOptions({ tracesSampler });
hub.bindClient(new BrowserClient(options));
// setting up the BrowserTracing integration normally automatically starts a pageload transaction, but that's not
// what we're testing here
createBrowserTracing(true, { startTransactionOnPageLoad: false });
mockChangeHistory({ to: 'here', from: 'there' });
expect(tracesSampler).toHaveBeenCalledWith(
expect.objectContaining({
location: dogParkLocation,
transactionContext: expect.objectContaining({ op: 'navigation' }),
}),
);
});
});
});