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:
When using
testEnvironment: 'node',jest-next-dynamiccomplains thatpreloadAllcannot be called on the client-side dynamic imports (while it works fine on the server-side dynamic imports)If we remove
jest-next-dynamicand the call to preloadAll, then the content of the server-side dynamic import is no longer in our snapshotsIf we go back to
testEnvironemnt: 'jsdom', then our ssr tests pass even if we refer towindowor 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.