File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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} ) ;
Original file line number Diff line number Diff line change 11export 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' } ) )
You can’t perform that action at this time.
0 commit comments