|
| 1 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 2 | +import { ClientScriptError } from '@components/scripts/errors' |
| 3 | +import { handleScriptError } from '@components/scripts/errors/handler' |
| 4 | +import { captureException } from '@sentry/browser' |
| 5 | + |
| 6 | +const isProdMock = vi.hoisted(() => vi.fn(() => false)) |
| 7 | + |
| 8 | +vi.mock('@sentry/browser', () => ({ |
| 9 | + captureException: vi.fn(), |
| 10 | +})) |
| 11 | + |
| 12 | +vi.mock('@components/scripts/utils/environmentClient', () => ({ |
| 13 | + isProd: isProdMock, |
| 14 | +})) |
| 15 | + |
| 16 | +const captureExceptionMock = vi.mocked(captureException) |
| 17 | +const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) |
| 18 | + |
| 19 | +describe('handleScriptError', () => { |
| 20 | + beforeEach(() => { |
| 21 | + vi.clearAllMocks() |
| 22 | + isProdMock.mockReturnValue(false) |
| 23 | + consoleErrorSpy.mockClear() |
| 24 | + }) |
| 25 | + |
| 26 | + it('reports exceptions to Sentry when running in production', () => { |
| 27 | + isProdMock.mockReturnValue(true) |
| 28 | + |
| 29 | + const result = handleScriptError(new Error('boom'), { |
| 30 | + scriptName: 'AppBootstrap', |
| 31 | + operation: 'init', |
| 32 | + }) |
| 33 | + |
| 34 | + expect(result).toBeInstanceOf(ClientScriptError) |
| 35 | + expect(captureExceptionMock).toHaveBeenCalledWith(result, { |
| 36 | + tags: { |
| 37 | + scriptName: 'AppBootstrap', |
| 38 | + operation: 'init', |
| 39 | + }, |
| 40 | + }) |
| 41 | + expect(consoleErrorSpy).not.toHaveBeenCalled() |
| 42 | + }) |
| 43 | + |
| 44 | + it('logs errors to the console instead of reporting when not in production', () => { |
| 45 | + const result = handleScriptError('network issue', { scriptName: 'AppBootstrap' }) |
| 46 | + |
| 47 | + expect(result).toBeInstanceOf(ClientScriptError) |
| 48 | + expect(consoleErrorSpy).toHaveBeenCalledWith('[AppBootstrap]:', result) |
| 49 | + expect(captureExceptionMock).not.toHaveBeenCalled() |
| 50 | + }) |
| 51 | +}) |
0 commit comments