Skip to content

Commit 251bed2

Browse files
test: handle non-serializable tracking payloads
1 parent 67962ed commit 251bed2

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

utils/tracking.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,21 @@ describe('trackUser', () => {
6161
trackUser('testuser');
6262

6363
expect(fetchMock).toHaveBeenCalledTimes(1);
64+
});
65+
it('reports format error for non-serializable JSON payload', () => {
66+
const consoleErrorMock = vi.spyOn(console, 'error').mockImplementation(() => {});
67+
const fetchMock = vi.fn();
68+
vi.stubGlobal('fetch', fetchMock);
69+
70+
const payload: Record<string, unknown> = {};
71+
payload.self = payload;
72+
73+
trackUser(payload as unknown as string);
74+
75+
expect(consoleErrorMock).toHaveBeenCalledWith(
76+
'Failed to format tracking payload',
77+
expect.any(TypeError),
78+
);
79+
expect(fetchMock).not.toHaveBeenCalled();
6480
});
6581
});

utils/tracking.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
11
export function trackUser(username: string) {
22
if (typeof navigator === 'undefined' || typeof window === 'undefined') return;
33

4-
const payload = JSON.stringify({ username });
4+
let payload: string;
5+
6+
try {
7+
payload = JSON.stringify({ username });
8+
} catch (error) {
9+
console.error('Failed to format tracking payload', error);
10+
return;
11+
}
512

613
const beaconQueued = navigator.sendBeacon
714
? navigator.sendBeacon('/api/track-user', new Blob([payload], { type: 'application/json' }))

0 commit comments

Comments
 (0)