Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

disableGlobalCatchBoundary.test.tsx

104 lines2.7 KB

1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { cleanup, render, screen } from '@testing-library/react'
3import { Component } from 'react'
4import {
5 RouterProvider,
6 createBrowserHistory,
7 createRootRoute,
8 createRoute,
9 createRouter,
10} from '../src'
11import type { ReactNode } from 'react'
12​
13import type { RouterHistory } from '../src'
14​
15function ThrowingComponent() {
16 throw new Error('Test error')
18​
19// Custom error boundary to catch errors that bubble up
20class TestErrorBoundary extends Component<
21 { children: ReactNode },
22 { hasError: boolean; error?: Error }
23> {
24 constructor(props: { children: ReactNode }) {
25 super(props)
26 this.state = { hasError: false }
27 }
28​
29 static getDerivedStateFromError(error: Error) {
30 return { hasError: true, error }
31 }
32​
33 render() {
34 if (this.state.hasError) {
35 return (
36 <div>External Error Boundary Caught: {this.state.error?.message}</div>
37 )
38 }
39​
40 return this.props.children
41 }
43​
44let history: RouterHistory
45let originalOnError: typeof window.onerror
46​
47beforeEach(() => {
48 history = createBrowserHistory()
49 originalOnError = window.onerror
50 expect(window.location.pathname).toBe('/')
51})
52​
53afterEach(() => {
54 history.destroy()
55 window.onerror = originalOnError
56 vi.resetAllMocks()
57 window.history.replaceState(null, 'root', '/')
58 cleanup()
59})
60​
61function createTestRouter(disableGlobalCatchBoundary: boolean) {
62 const rootRoute = createRootRoute()
63 const indexRoute = createRoute({
64 getParentRoute: () => rootRoute,
65 path: '/',
66 component: ThrowingComponent,
67 })
68​
69 const routeTree = rootRoute.addChildren([indexRoute])
70 return createRouter({
71 routeTree,
72 history,
73 disableGlobalCatchBoundary,
74 })
76​
77describe('disableGlobalCatchBoundary option', () => {
78 test('catches errors in global boundary when disableGlobalCatchBoundary is false', async () => {
79 const router = createTestRouter(false)
80​
81 render(<RouterProvider router={router} />)
82​
83 // The global CatchBoundary shows "Something went wrong!" by default
84 const errorElement = await screen.findByText('Something went wrong!')
85 expect(errorElement).toBeInTheDocument()
86 })
87​
88 test('errors bubble up to external error boundary when disableGlobalCatchBoundary is true', async () => {
89 const router = createTestRouter(true)
90​
91 // Wrap RouterProvider in an external error boundary
92 render(
93 <TestErrorBoundary>
94 <RouterProvider router={router} />
95 </TestErrorBoundary>,
96 )
97​
98 // Error should bubble up and be caught by the external error boundary
99 const externalErrorElement = await screen.findByText(
100 'External Error Boundary Caught: Test error',
101 )
102 expect(externalErrorElement).toBeInTheDocument()
103 })
104})