-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathhydratedRouter.test.ts
More file actions
199 lines (169 loc) · 7.22 KB
/
hydratedRouter.test.ts
File metadata and controls
199 lines (169 loc) · 7.22 KB
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
import * as browser from '@sentry/browser';
import * as core from '@sentry/core';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { instrumentHydratedRouter } from '../../src/client/hydratedRouter';
vi.mock('@sentry/core', async () => {
const actual = await vi.importActual<any>('@sentry/core');
return {
...actual,
getActiveSpan: vi.fn(),
getRootSpan: vi.fn(),
spanToJSON: vi.fn(),
getClient: vi.fn(),
debug: {
warn: vi.fn(),
},
SEMANTIC_ATTRIBUTE_SENTRY_OP: 'op',
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN: 'origin',
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE: 'source',
GLOBAL_OBJ: globalThis,
};
});
vi.mock('@sentry/browser', () => ({
startBrowserTracingNavigationSpan: vi.fn(),
}));
describe('instrumentHydratedRouter', () => {
let originalRouter: any;
let mockRouter: any;
let mockPageloadSpan: any;
let mockNavigationSpan: any;
beforeEach(() => {
originalRouter = (globalThis as any).__reactRouterDataRouter;
mockRouter = {
state: {
location: { pathname: '/foo/bar' },
matches: [{ route: { path: '/foo/:id' } }],
},
navigate: vi.fn(),
subscribe: vi.fn(),
};
(globalThis as any).__reactRouterDataRouter = mockRouter;
mockPageloadSpan = { updateName: vi.fn(), setAttributes: vi.fn() };
mockNavigationSpan = { updateName: vi.fn(), setAttributes: vi.fn() };
(core.getActiveSpan as any).mockReturnValue(mockPageloadSpan);
(core.getRootSpan as any).mockImplementation((span: any) => span);
(core.spanToJSON as any).mockImplementation((_span: any) => ({
description: '/foo/bar',
op: 'pageload',
}));
(core.getClient as any).mockReturnValue({});
(browser.startBrowserTracingNavigationSpan as any).mockReturnValue(mockNavigationSpan);
});
afterEach(() => {
(globalThis as any).__reactRouterDataRouter = originalRouter;
vi.clearAllMocks();
});
it('subscribes to the router and patches navigate', () => {
instrumentHydratedRouter();
expect(typeof mockRouter.navigate).toBe('function');
expect(mockRouter.subscribe).toHaveBeenCalled();
});
it('updates pageload transaction name if needed', () => {
instrumentHydratedRouter();
expect(mockPageloadSpan.updateName).toHaveBeenCalled();
expect(mockPageloadSpan.setAttributes).toHaveBeenCalled();
});
it('creates navigation transaction on navigate', () => {
instrumentHydratedRouter();
mockRouter.navigate('/bar');
expect(browser.startBrowserTracingNavigationSpan).toHaveBeenCalled();
});
it('updates navigation transaction on state change to idle', () => {
instrumentHydratedRouter();
// Simulate a state change to idle
const callback = mockRouter.subscribe.mock.calls[0][0];
const newState = {
location: { pathname: '/foo/bar' },
matches: [{ route: { path: '/foo/:id' } }],
navigation: { state: 'idle' },
};
mockRouter.navigate('/foo/bar');
// After navigation, the active span should be the navigation span
(core.getActiveSpan as any).mockReturnValue(mockNavigationSpan);
callback(newState);
expect(mockNavigationSpan.updateName).toHaveBeenCalled();
expect(mockNavigationSpan.setAttributes).toHaveBeenCalled();
});
it('does not update navigation transaction on state change to loading', () => {
instrumentHydratedRouter();
// Simulate a state change to loading (non-idle)
const callback = mockRouter.subscribe.mock.calls[0][0];
const newState = {
location: { pathname: '/foo/bar' },
matches: [{ route: { path: '/foo/:id' } }],
navigation: { state: 'loading' },
};
mockRouter.navigate('/foo/bar');
// After navigation, the active span should be the navigation span
(core.getActiveSpan as any).mockReturnValue(mockNavigationSpan);
callback(newState);
expect(mockNavigationSpan.updateName).not.toHaveBeenCalled();
expect(mockNavigationSpan.setAttributes).not.toHaveBeenCalled();
});
it('skips navigation span creation when client instrumentation API is enabled', () => {
// Simulate that the client instrumentation API is enabled
// (meaning the instrumentation API handles navigation spans and we should avoid double-counting)
(globalThis as any).__sentryReactRouterClientInstrumentationUsed = true;
instrumentHydratedRouter();
mockRouter.navigate('/bar');
// Should not create a navigation span because instrumentation API is handling it
expect(browser.startBrowserTracingNavigationSpan).not.toHaveBeenCalled();
// Clean up
delete (globalThis as any).__sentryReactRouterClientInstrumentationUsed;
});
it('creates navigation transaction with correct name when navigate is called with an object `to`', () => {
instrumentHydratedRouter();
mockRouter.navigate({ pathname: '/items/123', search: '?foo=bar' });
expect(browser.startBrowserTracingNavigationSpan).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
name: '/items/123',
}),
);
});
it('creates navigation transaction with correct name when navigate is called with a number', () => {
instrumentHydratedRouter();
mockRouter.navigate(-1);
expect(browser.startBrowserTracingNavigationSpan).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
name: '-1',
}),
);
});
it('creates navigation span when client instrumentation API is not enabled', () => {
// Ensure the flag is not set (default state - instrumentation API not used)
delete (globalThis as any).__sentryReactRouterClientInstrumentationUsed;
instrumentHydratedRouter();
mockRouter.navigate('/bar');
// Should create a navigation span because instrumentation API is not handling it
expect(browser.startBrowserTracingNavigationSpan).toHaveBeenCalled();
});
it('creates navigation span in Framework Mode (flag not set means router() was never called)', () => {
// This is a regression test for Framework Mode (e.g., Remix) where:
// 1. createSentryClientInstrumentation() may be called during SDK init
// 2. But the framework doesn't support unstable_instrumentations, so router() is never called
// 3. In this case, the legacy navigation instrumentation should still create spans
//
// We simulate this by ensuring the flag is NOT set (since router() was never called)
// Ensure the flag is NOT set (simulating that router() was never called)
delete (globalThis as any).__sentryReactRouterClientInstrumentationUsed;
instrumentHydratedRouter();
mockRouter.navigate('/bar');
// Should create a navigation span via legacy instrumentation because
// the instrumentation API's router() method was never called
expect(browser.startBrowserTracingNavigationSpan).toHaveBeenCalled();
});
it('should warn when router is not found after max retries', () => {
vi.useFakeTimers();
// Remove the router to simulate it not being available
delete (globalThis as any).__reactRouterDataRouter;
instrumentHydratedRouter();
// Advance timers past MAX_RETRIES (40 retries × 50ms = 2000ms)
vi.advanceTimersByTime(2100);
expect(core.debug.warn).toHaveBeenCalledWith(
'Unable to instrument React Router: router not found after hydration.',
);
vi.useRealTimers();
});
});