|
| 1 | +import React, { act } from "react"; |
| 2 | +import { createRoot, type Root } from "react-dom/client"; |
| 3 | +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; |
| 4 | + |
| 5 | +import { ExceptionlessErrorBoundary } from "../src/ExceptionlessErrorBoundary.js"; |
| 6 | + |
| 7 | +const mocks = vi.hoisted(() => ({ |
| 8 | + createException: vi.fn(), |
| 9 | + setContextProperty: vi.fn(), |
| 10 | + submit: vi.fn().mockResolvedValue(undefined) |
| 11 | +})); |
| 12 | + |
| 13 | +vi.mock("@exceptionless/browser", () => ({ |
| 14 | + Exceptionless: { |
| 15 | + createException: mocks.createException.mockImplementation(() => ({ |
| 16 | + setContextProperty: mocks.setContextProperty, |
| 17 | + submit: mocks.submit |
| 18 | + })) |
| 19 | + } |
| 20 | +})); |
| 21 | + |
| 22 | +function Crash(): React.ReactNode { |
| 23 | + throw new Error("Boom"); |
| 24 | +} |
| 25 | + |
| 26 | +describe("ExceptionlessErrorBoundary", () => { |
| 27 | + let container: HTMLDivElement; |
| 28 | + let root: Root; |
| 29 | + let consoleError: ReturnType<typeof vi.spyOn>; |
| 30 | + |
| 31 | + beforeEach(() => { |
| 32 | + vi.clearAllMocks(); |
| 33 | + consoleError = vi.spyOn(console, "error").mockImplementation(() => {}); |
| 34 | + container = document.createElement("div"); |
| 35 | + document.body.appendChild(container); |
| 36 | + root = createRoot(container); |
| 37 | + }); |
| 38 | + |
| 39 | + afterEach(() => { |
| 40 | + act(() => { |
| 41 | + root.unmount(); |
| 42 | + }); |
| 43 | + container.remove(); |
| 44 | + consoleError.mockRestore(); |
| 45 | + }); |
| 46 | + |
| 47 | + test("should render fallback content when a child throws", async () => { |
| 48 | + await act(async () => { |
| 49 | + root.render( |
| 50 | + <ExceptionlessErrorBoundary fallback={<p>Something went wrong.</p>}> |
| 51 | + <Crash /> |
| 52 | + </ExceptionlessErrorBoundary> |
| 53 | + ); |
| 54 | + await Promise.resolve(); |
| 55 | + }); |
| 56 | + |
| 57 | + expect(container.textContent).toBe("Something went wrong."); |
| 58 | + expect(mocks.createException).toHaveBeenCalledWith(expect.any(Error)); |
| 59 | + expect(mocks.setContextProperty).toHaveBeenCalled(); |
| 60 | + expect(mocks.submit).toHaveBeenCalled(); |
| 61 | + }); |
| 62 | + |
| 63 | + test("should render nothing by default when a child throws", async () => { |
| 64 | + await act(async () => { |
| 65 | + root.render( |
| 66 | + <ExceptionlessErrorBoundary> |
| 67 | + <Crash /> |
| 68 | + </ExceptionlessErrorBoundary> |
| 69 | + ); |
| 70 | + await Promise.resolve(); |
| 71 | + }); |
| 72 | + |
| 73 | + expect(container.textContent).toBe(""); |
| 74 | + expect(mocks.createException).toHaveBeenCalledWith(expect.any(Error)); |
| 75 | + expect(mocks.submit).toHaveBeenCalled(); |
| 76 | + }); |
| 77 | +}); |
0 commit comments