import { afterEach, describe, expect, it, vi } from 'vitest' import { sendFrontendMetric } from './frontend-metrics' describe('sendFrontendMetric', () => { afterEach(() => { vi.unstubAllGlobals() }) it.each(['pageview', 'global_crash'] as const)( 'posts a single %s event as a CORS-simple request', (metricName) => { const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 })) vi.stubGlobal('fetch', fetchMock) sendFrontendMetric(metricName) expect(fetchMock).toHaveBeenCalledTimes(1) const [url, init] = fetchMock.mock.calls[0] expect(url).toBe('https://misc-functions.vercel.app/api/metrics') expect(init).toMatchObject({ method: 'POST', keepalive: true, credentials: 'omit', headers: { 'Content-Type': 'text/plain' }, }) expect(JSON.parse(init.body)).toEqual({ environment: 'staging', events: [{ metric_name: metricName, value: 1, metadata: { app: 'studio' } }], }) } ) it('does not throw or leave an unhandled rejection when the request fails', async () => { const unhandled = vi.fn() process.on('unhandledRejection', unhandled) vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))) expect(() => sendFrontendMetric('global_crash')).not.toThrow() await new Promise((resolve) => setImmediate(resolve)) process.off('unhandledRejection', unhandled) expect(unhandled).not.toHaveBeenCalled() }) it('does not throw when fetch throws synchronously', () => { vi.stubGlobal( 'fetch', vi.fn(() => { throw new Error('boom') }) ) expect(() => sendFrontendMetric('global_crash')).not.toThrow() }) })