How do I mock client-side nextJs dynamic imports on the server side?

Viewed 386

This is a subtle variation to some questions that have been asked before. We're using jest to run some ssr tests:

module.exports = {
  testEnvironment: 'node',  // NOT jsdom
}

And our Next.JS components have a mixture of client-side dynamic imports, and server-side dynamic imports.

// server-side dynamic import
const Content = dynamic(() => import('../shared/Content'));
// client-side dynamic import
const LoginDialog = dynamic(() => import('../dialogs/LoginDialog'), {
  ssr: false,
});

The point is, when running the ssr test, since it's running on the server-side, our snapshot should include the content from the server-side dynamic import, and should not include the content from the client-side dynamic import.

But unfortunately we're running aground because we hit one of these cases:

  1. When using testEnvironment: 'node', jest-next-dynamic complains that preloadAll cannot be called on the client-side dynamic imports (while it works fine on the server-side dynamic imports)

  2. If we remove jest-next-dynamic and the call to preloadAll, then the content of the server-side dynamic import is no longer in our snapshots

  3. If we go back to testEnvironemnt: 'jsdom', then our ssr tests pass even if we refer to window or other browser-specific stuff on the server-side, which is very bad

So, the question is: how do we use jest and Next.JS to properly mock client-side dynamic imports while also continuing to implement server-side dynamic imports?

We also looked in to how to mock/spy next/dynamic using jest to only mock if ssr: true but it doesn't look like jest supports mocking depending on parameter values.

0 Answers
Related