FormidableLabs / FormidableLabs/jest-next-dynamic
Cannot read property 'preload' of undefined when testing with config testEnvironment: 'node' at jest
- Dominant language
- JavaScript
- Stars
- 70
- Forks
- 7
- PR merge metrics
- No merged PRs in 30d
Description
We are trying to set some SSR tests for our Next.js app to make sure that our server side rendering is working as expected. Some of the requirements of this is that the `window` object or the `document` object should be `undefined` in our environment.
To achieve this we have set our jest test environment to `node` at the config file `jest.config.js`:
```
module.exports = {
testEnvironment: 'node',
}
```
We have also set some dynamic imports at our app with the option `{ ssr: false }`, as we want them to be rendered on the client side:
```
const DynamicCustomComponent = dynamic(
() => import('../DynamicCustomComponent'),
{ ssr: false }
);
```
When having all the above specs we run into the following issue:
```
TypeError: Cannot read property 'preload' of undefined
35 |
36 | beforeAll(async () => {
> 37 | await preloadAll();
| ^
38 | });
39 |
40 | describe('SSR - Custom Page', () => {
at node_modules/jest-next-dynamic/index.js:40:38
at node_modules/jest-next-dynamic/index.js:12:52
at Array.map ()
at preloadAll (node_modules/jest-next-dynamic/index.js:12:37)
```
As far as I have researched, whats going on is that in a jest `node` environment is that we are trying to preload a SSR false dynamic component, which will be undefined as it should only be render in a client. So in conclusion `LoadableComponent` at line 35 at the file https://github.com/FormidableLabs/jest-next-dynamic/blob/master/index.js is `undefined`.
```
LoadableComponent.preload
? LoadableComponent.preload()
: LoadableComponent.render.preload();
```
Is there a way around to fix this? If we set the jest env too `jsdom` works but we NEED to set a `node` jest env to simulate a Server Side Rendering test, so that solution does not work for us.
I have tried locally the following change for lines 35, 36 and 37 at file https://github.com/FormidableLabs/jest-next-dynamic/blob/master/index.js that worked:
```
if(LoadableComponent.preload) {
LoadableComponent.preload();
} else if(LoadableComponent.render) {
LoadableComponent.render.preload();
}
```
Is this a possible fix for the library?
Contributor guide
Research direction
Start in index.js around preloadAll and lines 35-37, then reproduce the failure with the shown Jest node environment and an SSR-disabled dynamic component. Done means the preload step no longer throws for an unavailable component while existing preload behavior remains intact.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, next.js
- Domain
- testing-qa, web-dev
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 52/100