import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as Sentry from '@sentry/react'; import { SENTRY_TUNNEL_PATH, initSentry } from '@/lib/sentry'; import { resetAppConfigCache } from '@/lib/config'; // ESM namespace objects are not configurable, so Sentry.init cannot be spied on in place. vi.mock('@sentry/react', () => ({ init: vi.fn() })); const init = vi.mocked(Sentry.init); describe('initSentry', () => { beforeEach(() => { resetAppConfigCache(); init.mockClear(); }); afterEach(() => { vi.unstubAllEnvs(); resetAppConfigCache(); }); it('does nothing without a DSN, so local development is unaffected', () => { vi.stubEnv('VITE_SENTRY_DSN', undefined as unknown as string); initSentry(); expect(init).not.toHaveBeenCalled(); }); it('does nothing when the DSN is an empty string', () => { vi.stubEnv('VITE_SENTRY_DSN', ''); initSentry(); expect(init).not.toHaveBeenCalled(); }); /** * The tunnel is the whole reason browser reporting survives an ad blocker: a direct ingest URL * is blocked with ERR_BLOCKED_BY_CLIENT, losing errors precisely for the users who have one. */ it('routes through the same-origin tunnel rather than a Sentry ingest URL', () => { vi.stubEnv('VITE_SENTRY_DSN', 'https://abc@o1.ingest.de.sentry.io/42'); initSentry(); expect(init).toHaveBeenCalledOnce(); const options = init.mock.calls[0][0]!; expect(options.tunnel).toBe(SENTRY_TUNNEL_PATH); expect(options.tunnel).not.toContain('sentry.io'); }); it('tags the environment and the release, and keeps PII off', () => { vi.stubEnv('VITE_SENTRY_DSN', 'https://abc@o1.ingest.de.sentry.io/42'); vi.stubEnv('VITE_APP_ENV', 'test'); initSentry(); const options = init.mock.calls[0][0]!; expect(options.environment).toBe('test'); expect(options.release).toBeTruthy(); // False on the frontend even though the backend enables it with scrubbing: the browser // offers no equivalent in-process guarantee, and there is nothing here the backend cannot // already report. expect(options.sendDefaultPii).toBe(false); }); it('uses the same tunnel path the API serves and the dev proxy mirrors', () => { expect(SENTRY_TUNNEL_PATH).toBe('/sentry-tunnel'); expect(SENTRY_TUNNEL_PATH).not.toMatch(/^\/api\//); }); });