Skip to content

Commit e75f0cb

Browse files
test(tracking): add coverage for non-serializable JSON payloads
1 parent 8b8f47a commit e75f0cb

2 files changed

Lines changed: 15 additions & 19 deletions

File tree

utils/tracking.test.ts

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -118,20 +118,23 @@ describe('trackUser', () => {
118118

119119
expect(fetchMock).toHaveBeenCalledTimes(1);
120120
});
121-
it('reports format error for non-serializable JSON payload', () => {
122-
const consoleErrorMock = vi.spyOn(console, 'error').mockImplementation(() => {});
123-
const fetchMock = vi.fn();
124-
vi.stubGlobal('fetch', fetchMock);
121+
it('reports format error for non-serializable JSON payload', () => {
122+
const consoleErrorMock = vi.spyOn(console, 'error').mockImplementation(() => {});
123+
const fetchMock = vi.fn();
124+
vi.stubGlobal('fetch', fetchMock);
125125

126-
const payload: Record<string, unknown> = {};
127-
payload.self = payload;
126+
const payload: Record<string, unknown> = {};
127+
payload.self = payload;
128128

129-
trackUser(payload as unknown as string);
129+
trackUser(payload as unknown as string);
130130

131-
expect(consoleErrorMock).toHaveBeenCalledWith(
132-
'Failed to format tracking payload',
133-
expect.any(TypeError),
134-
);
131+
expect(consoleErrorMock).toHaveBeenCalledWith(
132+
'Failed to format tracking payload',
133+
expect.any(TypeError),
134+
);
135+
136+
expect(fetchMock).not.toHaveBeenCalled();
137+
});
135138

136139
it('handles non-serializable input gracefully without throwing', () => {
137140
// A circular reference cannot be serialized by JSON.stringify and will throw
@@ -189,4 +192,4 @@ describe('trackUser', () => {
189192
expect(sendBeaconMock).not.toHaveBeenCalled();
190193
expect(fetchMock).not.toHaveBeenCalled();
191194
});
192-
});
195+
});

utils/tracking.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,12 @@
11
export function trackUser(username: string) {
2-
if (!username || username.trim() === '') {
3-
return;
4-
}
52
if (typeof navigator === 'undefined' || typeof window === 'undefined') return;
63
if (!username) return;
7-
84
let payload: string;
95

106
try {
117
payload = JSON.stringify({ username });
128
} catch (error) {
139
console.error('Failed to format tracking payload', error);
14-
try {
15-
payload = JSON.stringify({ username });
16-
} catch {
1710
return;
1811
}
1912

0 commit comments

Comments
 (0)