FormidableLabs / jest-next-dynamic

Resolve Next.js dynamic import components in Jest tests
MIT License
69 stars 7 forks source link

Cannot read property 'preload' of undefined when testing with config testEnvironment: 'node' at jest #38

Open smhorta opened 2 years ago

smhorta commented 2 years ago

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 (<anonymous>)
      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?