Repository navigation
Expand file tree
/
Copy pathtracking.test.ts
More file actions
265 lines (202 loc) · 7.92 KB
/
Copy pathtracking.test.ts
File metadata and controls
265 lines (202 loc) · 7.92 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
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
import { afterEach, describe, expect, it, vi } from 'vitest';
import { trackUser } from './tracking';
const originalSendBeacon = navigator.sendBeacon;
describe('trackUser', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
Object.defineProperty(navigator, 'sendBeacon', {
value: originalSendBeacon,
configurable: true,
});
});
it('does not send when username is empty', () => {
const sendBeaconMock = vi.fn();
const fetchMock = vi.fn();
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
vi.stubGlobal('fetch', fetchMock);
trackUser('');
expect(sendBeaconMock).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it('uses sendBeacon when available', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
trackUser('testuser');
expect(sendBeaconMock).toHaveBeenCalledTimes(1);
expect(sendBeaconMock).toHaveBeenCalledWith('/api/track-user', expect.any(Blob));
});
it('should verify trackUser sends correct JSON payload structure via sendBeacon Blob content', async () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
trackUser('octocat');
expect(sendBeaconMock).toHaveBeenCalledTimes(1);
const callArguments = sendBeaconMock.mock.calls[0];
const blobPayload = callArguments[1] as Blob;
expect(blobPayload).toBeInstanceOf(Blob);
const textContent = await blobPayload.text();
const parsedJSON = JSON.parse(textContent);
expect(parsedJSON).toEqual({ username: 'octocat' });
});
it('falls back to fetch when sendBeacon is not available', () => {
Object.defineProperty(navigator, 'sendBeacon', {
value: undefined,
configurable: true,
});
const fetchMock = vi.fn().mockResolvedValue({});
vi.stubGlobal('fetch', fetchMock);
trackUser('testuser');
expect(fetchMock).toHaveBeenCalledWith('/api/track-user', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'testuser' }),
keepalive: true,
});
});
it('handles empty username without crashing', () => {
const sendBeaconMock = vi.fn().mockReturnValue(true);
const fetchMock = vi.fn();
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
vi.stubGlobal('fetch', fetchMock);
expect(() => trackUser('')).not.toThrow();
expect(sendBeaconMock).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it('falls back to fetch when sendBeacon returns false', () => {
const sendBeaconMock = vi.fn().mockReturnValue(false);
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
const fetchMock = vi.fn().mockResolvedValue({});
vi.stubGlobal('fetch', fetchMock);
trackUser('testuser');
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('reports format error for non-serializable JSON payload', () => {
const consoleErrorMock = vi.spyOn(console, 'error').mockImplementation(() => {});
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const payload: Record<string, unknown> = {};
payload.self = payload;
trackUser(payload as unknown as string);
expect(consoleErrorMock).toHaveBeenCalledWith(
'Failed to format tracking payload',
expect.any(TypeError)
);
expect(fetchMock).not.toHaveBeenCalled();
});
it('handles non-serializable input gracefully without throwing', () => {
// A circular reference cannot be serialized by JSON.stringify and will throw
// a TypeError. This test verifies that the utility does not propagate the
// exception to the caller.
const circular: Record<string, unknown> = {};
circular['self'] = circular;
const originalStringify = JSON.stringify;
vi.spyOn(JSON, 'stringify').mockImplementationOnce(() => {
throw new TypeError('Converting circular structure to JSON');
});
expect(() => trackUser('testuser')).not.toThrow();
JSON.stringify = originalStringify;
});
it('does not run in SSR context when window is undefined', () => {
const originalWindow = globalThis.window;
const sendBeaconMock = vi.fn();
const fetchMock = vi.fn();
Object.defineProperty(globalThis, 'window', {
value: undefined,
configurable: true,
});
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
vi.stubGlobal('fetch', fetchMock);
trackUser('octocat');
expect(sendBeaconMock).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
Object.defineProperty(globalThis, 'window', {
value: originalWindow,
configurable: true,
});
});
it('gracefully bypasses tracking when user metric logs are empty or falsy', () => {
const fetchMock = vi.fn().mockResolvedValue({});
vi.stubGlobal('fetch', fetchMock);
const sendBeaconMock = vi.fn().mockReturnValue(true);
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
trackUser('');
expect(sendBeaconMock).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe('JSON response serializer — boundary robustness (Variation 2)', () => {
it('reports format error for non-serializable JSON payloads like objects, sets, functions, bytes, NaN, Infinity, custom classes', () => {
const consoleErrorMock = vi.spyOn(console, 'error').mockImplementation(() => {});
class CustomClass {}
const circularStructure: Record<string, unknown> = {};
circularStructure['self'] = circularStructure;
const edgeCases = [
{ key: 'value', ref: circularStructure }, // object with circular ref
new Set([1, 2, 3]), // set
() => 'test', // function
new Uint8Array([10, 20]), // bytes
NaN,
Infinity,
new CustomClass(), // custom class
Symbol('test-symbol'), // Symbol (non-serializable) - FIXED: removed 10n BigInt
];
edgeCases.forEach((payload) => {
const originalStringify = JSON.stringify;
vi.spyOn(JSON, 'stringify').mockImplementationOnce(() => {
throw new TypeError('Simulated JSON serialization format error');
});
expect(() => trackUser(payload as unknown as string)).not.toThrow();
expect(consoleErrorMock).toHaveBeenCalledWith(
'Failed to format tracking payload',
expect.any(TypeError)
);
JSON.stringify = originalStringify;
});
consoleErrorMock.mockRestore();
});
});
describe('JSON response serializer — boundary robustness (Variation 3)', () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('verifies the utility catches the exception and reports format errors when passed non-serializable JSON payloads', () => {
const sendBeaconMock = vi.fn().mockReturnValue(false);
Object.defineProperty(navigator, 'sendBeacon', {
value: sendBeaconMock,
configurable: true,
});
const fetchMock = vi.fn().mockResolvedValue({});
vi.stubGlobal('fetch', fetchMock);
// Arrange: Create a non-serializable payload using a circular reference
const circularStructure: Record<string, unknown> = {};
circularStructure['self'] = circularStructure;
// Provide a trim method that returns the circular structure to trigger the serialization error
const nonSerializablePayload = {
trim: () => circularStructure,
};
// Act & Assert: Invoke the utility with the target inputs and verify it handles it gracefully
expect(() => trackUser(nonSerializablePayload as unknown as string)).not.toThrow();
});
});