fix(tracker-web): telemetry test mock setup for process.env and document.addEventListener

This commit is contained in:
saravanakumardb1 2026-03-02 09:17:51 -08:00
parent faca108813
commit 0ee0533699

View File

@ -5,6 +5,12 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock process.env BEFORE importing telemetry module (hoisted)
const mockProductId = vi.hoisted(() => 'test-product');
vi.stubGlobal('process', {
env: { NEXT_PUBLIC_PRODUCT_ID: mockProductId },
});
// Mock browser globals before importing the module
const mockSendBeacon = vi.fn().mockReturnValue(true);
const mockFetch = vi.fn().mockResolvedValue({ ok: true });
@ -23,7 +29,10 @@ vi.stubGlobal('localStorage', {
removeItem: (key: string) => mockLocalStorage.delete(key),
});
vi.stubGlobal('document', { visibilityState: 'visible' });
vi.stubGlobal('document', {
visibilityState: 'visible',
addEventListener: mockAddEventListener,
});
vi.stubGlobal('window', {
addEventListener: mockAddEventListener,
});
@ -111,10 +120,7 @@ describe('flush', () => {
trackEvent('info', 'test', 'test_event');
flush();
expect(mockSendBeacon).toHaveBeenCalledWith(
'/api/telemetry/ingest',
expect.any(String),
);
expect(mockSendBeacon).toHaveBeenCalledWith('/api/telemetry/ingest', expect.any(String));
});
it('falls back to fetch when sendBeacon fails', () => {
@ -124,7 +130,7 @@ describe('flush', () => {
expect(mockFetch).toHaveBeenCalledWith(
'/api/telemetry/ingest',
expect.objectContaining({ method: 'POST', keepalive: true }),
expect.objectContaining({ method: 'POST', keepalive: true })
);
});
@ -153,10 +159,7 @@ describe('initTelemetry', () => {
it('registers visibilitychange listener', () => {
initTelemetry();
expect(mockAddEventListener).toHaveBeenCalledWith(
'visibilitychange',
expect.any(Function),
);
expect(mockAddEventListener).toHaveBeenCalledWith('visibilitychange', expect.any(Function));
});
it('tracks session_started event', () => {
@ -165,7 +168,7 @@ describe('initTelemetry', () => {
const payload = JSON.parse(mockSendBeacon.mock.calls[0][1]);
const sessionEvent = payload.events.find(
(e: Record<string, string>) => e.eventName === 'session_started',
(e: Record<string, string>) => e.eventName === 'session_started'
);
expect(sessionEvent).toBeDefined();
expect(sessionEvent.module).toBe('app_lifecycle');