|
3 | 3 | Unlike [react-loadable](https://github.com/jamiebuilds/react-loadable), the |
4 | 4 | [dynamic import](https://github.com/zeit/next.js#dynamic-import) support |
5 | 5 | offered by Next.js does not expose a way to preload the dynamically imported |
6 | | -components in Jest’s environment (which mimics a DOM environment). |
| 6 | +components in Jest’s environment (which mimics a DOM environment). Even if you |
| 7 | +get a handle on the `Loadable` component bundled with Next.js, it skips queuing |
| 8 | +up the components in DOM-like environments. Bummer! |
7 | 9 |
|
8 | | -This module can be imported in your tests or setup file to make sure any |
| 10 | +This module can be imported in your test or setup files to make sure any |
9 | 11 | component created with `next/dynamic` is added to a queue, which can then be |
10 | 12 | flushed with the exported `preloadAll` function. |
11 | 13 |
|
| 14 | +Using this, your component tests (including snapshots) can render the full |
| 15 | +component tree instead of the loading placeholders. |
| 16 | + |
| 17 | +## Setup |
| 18 | + |
| 19 | +In order to transform `import()` successfully in Jest’s environment, you must |
| 20 | +use a different transform than the one provided by `next/babel` (which expects |
| 21 | +to be built with webpack). |
| 22 | + |
| 23 | +Both of these work fine: |
| 24 | + |
| 25 | +- [babel-plugin-dynamic-import-node](https://www.npmjs.com/package/babel-plugin-dynamic-import-node) |
| 26 | +- [babel-plugin-transform-dynamic-import](https://www.npmjs.com/package/babel-plugin-transform-dynamic-import) |
| 27 | + |
| 28 | +```json |
| 29 | +{ |
| 30 | + "plugins": ["babel-plugin-dynamic-import-node]"] |
| 31 | +} |
| 32 | +``` |
| 33 | + |
12 | 34 | ## Usage |
13 | 35 |
|
14 | 36 | ```js |
15 | 37 | // This will mock `next/dynamic`, so make sure to import it before any of your |
16 | 38 | // components. |
17 | 39 | import preloadAll from "jest-next-dynamic"; |
| 40 | +// This component can have dynamic imports anywhere in its rendered tree, |
| 41 | +// including nested dynamic imports. |
| 42 | +import SomeComponent from "./SomeComponent"; |
18 | 43 |
|
19 | 44 | beforeAll(async () => { |
20 | 45 | await preloadAll(); |
21 | 46 | }); |
| 47 | + |
| 48 | +// Your tests here! |
22 | 49 | ``` |
0 commit comments