@@ -15,23 +15,37 @@ module.exports = function preloadAll() {
15
15
}
16
16
} ;
17
17
18
- jest . doMock (
19
- "next/dynamic" ,
20
- ( ) => {
21
- const { default : dynamic } = jest . requireActual ( "next/dynamic" ) ;
18
+ function createFactory ( moduleName ) {
19
+ return ( ) => {
20
+ const dynamicModule = jest . requireActual ( moduleName ) ;
21
+ const dynamic = dynamicModule . default ;
22
22
23
- const mockDynamic = ( ...args ) => {
24
- const LoadableComponent = dynamic ( ...args ) ;
23
+ const mockDynamic = ( loader , options ) => {
24
+ // Remove webpack-specific functionality added by the next/babel preset.
25
+ if ( loader && typeof loader === "object" && loader . loadableGenerated ) {
26
+ const { loadableGenerated, ...mockLoader } = loader ;
27
+ loader = mockLoader ;
28
+ }
29
+ if ( options && typeof options === "object" && options . loadableGenerated ) {
30
+ const { loadableGenerated, ...mockOptions } = options ;
31
+ options = mockOptions ;
32
+ }
33
+ const LoadableComponent = dynamic ( loader , options ) ;
25
34
mockInitializers . push ( ( ) => LoadableComponent . preload ( ) ) ;
26
35
return LoadableComponent ;
27
36
} ;
28
37
29
- return mockDynamic ;
30
- } ,
31
- // In order to more easily include this feature in shared Jest setups (like
32
- // presets), use `virtual: true` to avoid throwing an error when `next` isn't
33
- // actually installed.
34
- {
35
- virtual : true
36
- }
37
- ) ;
38
+ // Replace the `default` export on the existing module so that other exports
39
+ // and non-enumerable properties remain.
40
+ dynamicModule . default = mockDynamic ;
41
+ return dynamicModule ;
42
+ } ;
43
+ }
44
+
45
+ // In order to more easily include this feature in shared Jest setups (like
46
+ // presets), use `virtual: true` to avoid throwing an error when `next` isn't
47
+ // actually installed or it's a version without `next-server` (introduced in
48
+ // Next.js 8).
49
+ for ( const moduleName of [ "next/dynamic" , "next-server/dynamic" ] ) {
50
+ jest . doMock ( moduleName , createFactory ( moduleName ) , { virtual : true } ) ;
51
+ }
0 commit comments