1+ import { render , screen } from '@testing-library/react' ;
2+ import * as React from 'react' ;
3+
4+ import { ChunkLoadErrorBoundary } from './chunk-load-error-boundary' ;
5+
6+ // Suppress React's console.error for expected thrown errors in tests.
7+ beforeEach ( ( ) => jest . spyOn ( console , 'error' ) . mockImplementation ( ( ) => { } ) ) ;
8+ afterEach ( ( ) => jest . restoreAllMocks ( ) ) ;
9+
10+ function Bomb ( { error} : { error : Error } ) {
11+ throw error ;
12+ return null ; // unreachable; satisfies TS
13+ }
14+
15+ describe ( 'ChunkLoadErrorBoundary' , ( ) => {
16+ const reloadSpy = jest . fn ( ) ;
17+
18+ beforeEach ( ( ) => {
19+ Object . defineProperty ( window , 'location' , {
20+ writable : true ,
21+ value : { reload : reloadSpy }
22+ } ) ;
23+ reloadSpy . mockClear ( ) ;
24+ } ) ;
25+
26+ it ( 'renders children when there is no error' , ( ) => {
27+ render (
28+ < ChunkLoadErrorBoundary >
29+ < span > hello</ span >
30+ </ ChunkLoadErrorBoundary >
31+ ) ;
32+ expect ( screen . getByText ( 'hello' ) ) . toBeTruthy ( ) ;
33+ } ) ;
34+
35+ it ( 'triggers window.location.reload on a ChunkLoadError' , ( ) => {
36+ const chunkError = Object . assign ( new Error ( 'Loading chunk 775 failed.' ) , { name : 'ChunkLoadError' } ) ;
37+ render (
38+ < ChunkLoadErrorBoundary >
39+ < Bomb error = { chunkError } />
40+ </ ChunkLoadErrorBoundary >
41+ ) ;
42+ expect ( reloadSpy ) . toHaveBeenCalledTimes ( 1 ) ;
43+ expect ( screen . getByText ( / R e l o a d i n g / i) ) . toBeTruthy ( ) ;
44+ } ) ;
45+
46+ it ( 're-throws non-chunk errors for parent boundaries to handle' , ( ) => {
47+ const genericError = new Error ( 'Some other error' ) ;
48+ expect ( ( ) =>
49+ render (
50+ < ChunkLoadErrorBoundary >
51+ < Bomb error = { genericError } />
52+ </ ChunkLoadErrorBoundary >
53+ )
54+ ) . toThrow ( 'Some other error' ) ;
55+ expect ( reloadSpy ) . not . toHaveBeenCalled ( ) ;
56+ } ) ;
57+ } ) ;
58+
59+ describe ( 'ChunkLoadErrorBoundary.isChunkLoadError' , ( ) => {
60+ it . each ( [
61+ [ Object . assign ( new Error ( 'Loading chunk 775 failed.' ) , { name : 'ChunkLoadError' } ) , true ] ,
62+ [ new Error ( 'Loading chunk 42 failed.' ) , true ] ,
63+ [ new Error ( 'Loading CSS chunk 3 failed.' ) , true ] ,
64+ [ new Error ( 'Something unrelated' ) , false ] ,
65+ [ new Error ( 'TypeError: Cannot read property' ) , false ]
66+ ] ) ( 'correctly classifies %s as %s' , ( error , expected ) => {
67+ expect ( ChunkLoadErrorBoundary . isChunkLoadError ( error ) ) . toBe ( expected ) ;
68+ } ) ;
69+ } ) ;
0 commit comments