forked from getsentry/sentry-javascript
/
client.test.ts
313 lines (284 loc) · 10.2 KB
/
client.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
import { WINDOW } from '@sentry/react';
import { Transaction } from '@sentry/types';
import { JSDOM } from 'jsdom';
import { NEXT_DATA as NextData } from 'next/dist/next-server/lib/utils';
import { default as Router } from 'next/router';
import { nextRouterInstrumentation } from '../../src/performance/client';
const globalObject = WINDOW as typeof WINDOW & {
__BUILD_MANIFEST?: {
sortedPages?: string[];
};
};
const originalBuildManifest = globalObject.__BUILD_MANIFEST;
const originalBuildManifestRoutes = globalObject.__BUILD_MANIFEST?.sortedPages;
let eventHandlers: { [eventName: string]: Set<(...args: any[]) => void> } = {};
jest.mock('next/router', () => {
return {
default: {
events: {
on(type: string, handler: (...args: any[]) => void) {
if (!eventHandlers[type]) {
eventHandlers[type] = new Set();
}
eventHandlers[type].add(handler);
},
off: jest.fn((type: string, handler: (...args: any[]) => void) => {
if (eventHandlers[type]) {
eventHandlers[type].delete(handler);
}
}),
emit(type: string, ...eventArgs: any[]) {
if (eventHandlers[type]) {
eventHandlers[type].forEach(eventHandler => {
eventHandler(...eventArgs);
});
}
},
},
},
};
});
function createMockStartTransaction() {
return jest.fn(
() =>
({
startChild: () => ({
finish: () => undefined,
}),
finish: () => undefined,
} as Transaction),
);
}
describe('nextRouterInstrumentation', () => {
const originalGlobalDocument = WINDOW.document;
const originalGlobalLocation = WINDOW.location;
function setUpNextPage(pageProperties: {
url: string;
route: string;
query?: any;
props?: any;
navigatableRoutes?: string[];
hasNextData: boolean;
}) {
const nextDataContent: NextData = {
props: pageProperties.props,
page: pageProperties.route,
query: pageProperties.query,
buildId: 'y76hvndNJBAithejdVGLW',
isFallback: false,
gssp: true,
appGip: true,
scriptLoader: [],
};
const dom = new JSDOM(
// Just an example of what a __NEXT_DATA__ tag might look like
pageProperties.hasNextData
? `<body><script id="__NEXT_DATA__" type="application/json">${JSON.stringify(nextDataContent)}</script></body>`
: '<body><h1>No next data :(</h1></body>',
{ url: pageProperties.url },
);
// The Next.js routing instrumentations requires a few things to be present on pageload:
// 1. Access to window.document API for `window.document.getElementById`
// 2. Access to window.location API for `window.location.pathname`
Object.defineProperty(WINDOW, 'document', { value: dom.window.document, writable: true });
Object.defineProperty(WINDOW, 'location', { value: dom.window.document.location, writable: true });
// Define Next.js clientside build manifest with navigatable routes
globalObject.__BUILD_MANIFEST = {
...globalObject.__BUILD_MANIFEST,
sortedPages: pageProperties.navigatableRoutes as string[],
};
}
afterEach(() => {
// Clean up JSDom
Object.defineProperty(WINDOW, 'document', { value: originalGlobalDocument });
Object.defineProperty(WINDOW, 'location', { value: originalGlobalLocation });
// Reset Next.js' __BUILD_MANIFEST
globalObject.__BUILD_MANIFEST = originalBuildManifest;
if (globalObject.__BUILD_MANIFEST) {
globalObject.__BUILD_MANIFEST.sortedPages = originalBuildManifestRoutes as string[];
}
// Clear all event handlers
eventHandlers = {};
// Necessary to clear all Router.events.off() mock call numbers
jest.clearAllMocks();
});
describe('pageload transactions', () => {
it.each([
[
'https://example.com/lforst/posts/1337?q=42',
'/[user]/posts/[id]',
{ user: 'lforst', id: '1337', q: '42' },
{
pageProps: {
_sentryTraceData: 'c82b8554881b4d28ad977de04a4fb40a-a755953cd3394d5f-1',
_sentryBaggage: 'other=vendor,foo=bar,third=party,last=item,sentry-release=2.1.0,sentry-environment=myEnv',
},
},
true,
{
name: '/[user]/posts/[id]',
op: 'pageload',
tags: {
'routing.instrumentation': 'next-router',
},
metadata: {
source: 'route',
dynamicSamplingContext: { environment: 'myEnv', release: '2.1.0' },
},
traceId: 'c82b8554881b4d28ad977de04a4fb40a',
parentSpanId: 'a755953cd3394d5f',
parentSampled: true,
},
],
[
'https://example.com/some-page',
'/some-page',
{},
{
pageProps: {
_sentryTraceData: 'c82b8554881b4d28ad977de04a4fb40a-a755953cd3394d5f-1',
_sentryBaggage: 'other=vendor,foo=bar,third=party,last=item,sentry-release=2.1.0,sentry-environment=myEnv',
},
},
true,
{
name: '/some-page',
op: 'pageload',
tags: {
'routing.instrumentation': 'next-router',
},
metadata: {
source: 'route',
dynamicSamplingContext: { environment: 'myEnv', release: '2.1.0' },
},
traceId: 'c82b8554881b4d28ad977de04a4fb40a',
parentSpanId: 'a755953cd3394d5f',
parentSampled: true,
},
],
[
'https://example.com/',
'/',
{},
{},
true,
{
name: '/',
op: 'pageload',
tags: {
'routing.instrumentation': 'next-router',
},
metadata: {
source: 'route',
},
},
],
[
'https://example.com/lforst/posts/1337?q=42',
'/',
{},
{},
false, // no __NEXT_DATA__ tag
{
name: '/lforst/posts/1337',
op: 'pageload',
tags: {
'routing.instrumentation': 'next-router',
},
metadata: {
source: 'url',
},
},
],
])(
'creates a pageload transaction (#%#)',
(url, route, query, props, hasNextData, expectedStartTransactionArgument) => {
const mockStartTransaction = createMockStartTransaction();
setUpNextPage({ url, route, query, props, hasNextData });
nextRouterInstrumentation(mockStartTransaction);
expect(mockStartTransaction).toHaveBeenCalledTimes(1);
expect(mockStartTransaction).toHaveBeenLastCalledWith(expectedStartTransactionArgument);
},
);
it('does not create a pageload transaction if option not given', () => {
const mockStartTransaction = createMockStartTransaction();
setUpNextPage({ url: 'https://example.com/', route: '/', hasNextData: false });
nextRouterInstrumentation(mockStartTransaction, false);
expect(mockStartTransaction).toHaveBeenCalledTimes(0);
});
});
describe('new navigation transactions', () => {
it.each([
['/news', '/news', 'route'],
['/news/', '/news', 'route'],
['/some-route-that-is-not-defined-12332', '/some-route-that-is-not-defined-12332', 'url'], // unknown route
['/posts/42', '/posts/[id]', 'route'],
['/posts/42/', '/posts/[id]', 'route'],
['/posts/42?someParam=1', '/posts/[id]', 'route'], // query params are ignored
['/posts/42/details', '/posts/[id]/details', 'route'],
['/users/1337/friends/closeby/good', '/users/[id]/friends/[...filters]', 'route'],
['/users/1337/friends', '/users/1337/friends', 'url'],
['/statistics/page-visits', '/statistics/[[...parameters]]', 'route'],
['/statistics', '/statistics/[[...parameters]]', 'route'],
['/a/b/c/d', '/[a]/b/[c]/[...d]', 'route'],
['/a/b/c/d/e', '/[a]/b/[c]/[...d]', 'route'],
['/a/b/c', '/a/b/c', 'url'],
['/e/f/g/h', '/e/[f]/[g]/[[...h]]', 'route'],
['/e/f/g/h/i', '/e/[f]/[g]/[[...h]]', 'route'],
['/e/f/g', '/e/[f]/[g]/[[...h]]', 'route'],
])(
'should create a parameterized transaction on route change (%s)',
(targetLocation, expectedTransactionName, expectedTransactionSource) => {
const mockStartTransaction = createMockStartTransaction();
setUpNextPage({
url: 'https://example.com/home',
route: '/home',
hasNextData: true,
navigatableRoutes: [
'/home',
'/news',
'/posts/[id]',
'/posts/[id]/details',
'/users/[id]/friends/[...filters]',
'/statistics/[[...parameters]]',
// just some complicated routes to see if we get the matching right
'/[a]/b/[c]/[...d]',
'/e/[f]/[g]/[[...h]]',
],
});
nextRouterInstrumentation(mockStartTransaction, false, true);
Router.events.emit('routeChangeStart', targetLocation);
expect(mockStartTransaction).toHaveBeenCalledTimes(1);
expect(mockStartTransaction).toHaveBeenCalledWith(
expect.objectContaining({
name: expectedTransactionName,
op: 'navigation',
tags: expect.objectContaining({
'routing.instrumentation': 'next-router',
}),
metadata: expect.objectContaining({
source: expectedTransactionSource,
}),
}),
);
Router.events.emit('routeChangeComplete', targetLocation);
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(Router.events.off).toHaveBeenCalledWith('routeChangeComplete', expect.anything());
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(Router.events.off).toHaveBeenCalledTimes(1);
},
);
it('should not create transaction when navigation transactions are disabled', () => {
const mockStartTransaction = createMockStartTransaction();
setUpNextPage({
url: 'https://example.com/home',
route: '/home',
hasNextData: true,
navigatableRoutes: ['/home', '/posts/[id]'],
});
nextRouterInstrumentation(mockStartTransaction, false, false);
Router.events.emit('routeChangeStart', '/posts/42');
expect(mockStartTransaction).not.toHaveBeenCalled();
});
});
});