next.js: dynamic import not working in test environment

Bug report

Describe the bug

I have upgraded next.js from version 6 to 7, and running tests with jest now exits with the following: TypeError: require.resolveWeak is not a function

To Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Clone https://github.com/giovannigiordano/next.js/tree/master/examples/with-jest
  2. Install dependencies
  3. Run yarn test
  4. See error

Expected behavior

I expect testing dynamic import as would work as for version 6

Screenshots

https://i.imgur.com/i3aw7Eg.png

System information

  • OS: macOS Mojave 10.14
  • Version of Next.js: 7.0.1

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 9
  • Comments: 41 (21 by maintainers)

Most upvoted comments

heya, we’ve recently published a package that also mocks next/dynamic, but actually lets you render the resulting dynamic components: https://github.com/FormidableLabs/jest-next-dynamic

The idea is:

  1. Import the real next/dynamic, but wrap it and capture the Loadable component’s preload function.
  2. Add all preload initializers to a queue.
  3. Export a preloadAll function that will flush the queue.

From there, you just need to call beforeAll(preloadAll) and it will be as if the dynamic components were all already available – meaning they actually render, appear in snapshots instead of “loading…”, etc. This is exactly how you’d do it with react-loadable’s built-in Loadable.preloadAll method.

Similar to the approach above, by mocking the next/dynamic module and flushing a queue of every dynamic component, you don’t have to track down and export every single one in order to get at its preload method. 😃

Hope that helps someone!

(* Since the default Jest environment simulates a DOM environment, even if you get a handle on Loadable’s built-in preloadAll method, it won’t actually work due to this line which skips enqueuing the preload initializers – since in a Jest DOM environment, window will be defined.)

FWIW, here’s the fix we’ve implemented inside jest.setup.js on my team. The advantage is that it’s set up globally for all our tests.

// Manually mock next/dynamic as the next.js (7.0.2) babel plugin will compile to Webpack
// lazy imports (require.resolveWeak) who're conflicting with the Node module system.
jest.mock('next/dynamic', () => () => {
    const DynamicComponent = () => null;
    DynamicComponent.displayName = 'LoadableComponent';
    DynamicComponent.preload = jest.fn();
    return DynamicComponent;
});

The behavior should be exactly the same as before as the dynamic weren’t ever processed (even inside snapshots if you have some)

Hi @Timer, I’m not sure this issue should be closed. I’m still facing this issue (same error as in the first post). I’ve made a minimal reproducible version here: https://github.com/ellsclytn/next-with-jest

A clone, install all deps, and yarn test/npm run test will show it. This particular version has all dependencies updated to their latest at the time of writing.

This was fixed recently in Next.js 8.1 or 9, I cannot recall exactly.

this is how i hacked it,

const TodosList =
  process.env.NODE_ENV === "test"
    ? require("../components/TodosList").default
    : dynamic({
        loader: () => import("../components/TodosList"),
        loading: () => <p>loading ...</p>,
        ssr: true
      });

Since the release 9.1.2, I have this error in all of my test js with a dynamic component I have this error: TypeError: LoadableComponent.preload is not a function.

Did you have this problem ?

also got the same error in next 9.0.

I use typescript and added "babel-plugin-dynamic-import-node", to the plugins in test-env.

my babelrc looks like this:

{
  plugins: ["babel-plugin-styled-components"],
  env: {
    development: {
      presets: ["next/babel", "@zeit/next-typescript/babel", "@babel/preset-typescript"],
      plugins: ["ts-optchain"],
    },
    production: {
      presets: ["next/babel", "@zeit/next-typescript/babel", "@babel/preset-typescript"],
      plugins: ["ts-optchain"],
    },
    test: {
      presets: [
        [
          "next/babel",
          {
            "preset-env": {
              modules: "commonjs",
            },
          },
        ],
        "@zeit/next-typescript/babel",
        "@babel/preset-typescript",
      ],

      plugins: ["babel-plugin-dynamic-import-node", "ts-optchain"],
    },
  },
}

EDIT: using https://github.com/FormidableLabs/jest-next-dynamic solved the issue for me

@HeroProtagonist actually I have mocked next/dynamic and added babel-plugin-transform-dynamic-import.

Hi, Is there any update regarding this problem? Using jest-next-dynamic is a bit hacky and it does not work fine with shallow render in test.

Just wanted to give a quick link to a CodeSandbox repro:

https://codesandbox.io/s/4j3lw8lj20

If you fork this and open a new terminal and run yarn jest you can see the dynamic import fail. Maybe there is a config step missing here?

@jhoffmcd I kept tinkering with it, took an approach of having separate tsconfig from this repo: https://github.com/deptno/next.js-typescript-starter-kit.

Forked/revised sandbox (https://codesandbox.io/s/949zpj8yw) seems to be working. I don’t know if this is the right/best approach but… it works?

Oh and as far as advising the Next.js team on a potential built-in solution for this:

  1. I think there are already accommodations made in the Babel preset when the NODE_ENV is set to test – maybe the custom import Babel plugin is another thing to switch out there? Currently the import plugin pretty much depends on webpack, but it’s rare to use webpack for tests.
  2. Sync up with the latest react-loadable implementation, which enqueues preload initializers even on the client (no typeof window check).
  3. Expose preloadAll as an export of next/dynamic. Right now it’s possible to call preload on individual dynamic() results, but preloadAll isn’t exposed as an API anywhere (unless you reach into dist folders to find loadable.js).

@Emiliano-Bucci Feel free to open a new issue with a reproduction that we can take a look at 🙏

same issue here and the dynamic imports returns this

image

@damusnet Can you see test it with the .babelrc in this codesandbox 🙏

it looks like this:

{
  "presets": [
    "next/babel"
  ],
  "env": {
    "test": {
      "presets": [
        [
          "next/babel",
          {
            "transform-runtime": {
              "corejs": false
            }
          }
        ]
      ],
      "plugins": [
        "babel-plugin-dynamic-import-node"
      ],
    }
  }
}

This used to work for me without any change to the code or .babelrc, but next@9.0.1 breaks my tests again. (see https://github.com/zeit/next.js/issues/7872).

{
  "presets": ["next/babel"],
  "env": {
    "test": {
      "plugins": ["babel-plugin-dynamic-import-node"]
    }
  }
}

makes them pass again but seems unfortunate as it means that tests and code don’t use the same config anymore. And using babel-plugin-dynamic-import-node in all environments seems to disable the dynamic loading altogether (i.e. everything works but no chunks are loaded).

@lfades I’m having the same issue as originally posted but can’t seem to fix it by adding jest-next-dynamic, babel-plugin-dynamic-import-node and using the .babelrc setup you suggested.

I upgraded to 8.1.0 without any difference, still getting the original TypeError: require.resolveWeak is not a function error. Any ideas on how I can continue to debug this?

Here’s a working sandbox: https://codesandbox.io/s/nextdynamictestingissue-siuvx using a fork from @jhoffmcd sandbox.

The only change I did was to .babelrc:

{
  "presets": [
    "next/babel",
    "@zeit/next-typescript/babel"
  ],
  "env": {
    "test": {
      "plugins": [
        "babel-plugin-dynamic-import-node"
      ]
    }
  }
}

Using next@8.1.0, it also works in the latest canary. Please let me know if it’s working.

indeed sorry, here there is my solution:

jest.mock('next/dynamic', () => () => {
  const SimpleDrawer =
    // eslint-disable-next-line global-require
    require('../../../../../src/components/Navigation/SimpleDrawer').default;

  return props => (
    <SimpleDrawer {...props} />
  );
});```