question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Can't test with dynamic imported components

See original GitHub issue

What version of Next.js are you using?

11.1.2

What version of Node.js are you using?

16.12.0

What browser are you using?

No browser

What operating system are you using?

MacOS

How are you deploying your application?

No deployment

Describe the Bug

Running jest with a simple config along with @testing-library/react on a component that imports other components using next/dynamic won’t work.

The rendered HTML during the test run will never load the dynamic components even if those are directly used.

Expected Behavior

I would expect the dynamic components to be loaded when running the tests, or to be preloaded when NODE_ENV=test.

To Reproduce

  1. Create a page file under pages/index.js that imports a component dynamically:
import dynamic from "next/dynamic";

const MyComp = dynamic(() => import("../components/MyComp"));

export default function Home() {
  return <MyComp />;
}
  1. Create the component components/MyComp.js:
const Comp = () => {
  return <h1>Hello</h1>;
};

export default Comp;
  1. Add a test script to package.json that uses jest:
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"
  },
  1. Add a test file for the page in __tests__/pages/index.test.jsx:
import { render } from "@testing-library/react";

import Home from "../pages/index";

describe("Test main", () => {
  it("Home test", () => {
    const { getByText } = render(<Home />);

    expect(getByText("Hello")).toBeInTheDocument();
  });
});
  1. Add a simple jest.config.js file to run tests:
module.exports = {
  testEnvironment: "jsdom",
  transformIgnorePatterns: ["node_modules"],
  moduleFileExtensions: ["js", "jsx"],
  transform: {
    "^.+\\.(js|jsx)?$": "babel-jest"
  }
};
  1. Add a simple .babelrc config:
{
  "presets": ["next/babel"]
}

Now run the script npm run test or yarn test, the test won’t pass and will show this HTML in console:

  ● Test main › Home test

    TestingLibraryElementError: Unable to find an element with the text: Hello. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

    Ignored nodes: comments, <script />, <style />
    <body>
      <div />
    </body>

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
mattbooncommented, Oct 27, 2021

I fixed the testing of dynamic components in Jest using this package: https://github.com/FormidableLabs/jest-next-dynamic

Add this to the very top of any test files using next/dynamic components

// Note: must be imported *before* any imports containing next/dynamic components
import preloadAll from 'jest-next-dynamic' 

Then use the beforeAll took to register before tests are run

describe('example test', () => {
  beforeAll(async () => {
    await preloadAll()
  })

  ...
})
0reactions
github-actions[bot]commented, Feb 25, 2022

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing in Next.js: Dynamic Imports
The first thing you will need is to configure Babel to transpile dynamic imports to something Node. js can understand, to do so...
Read more >
How to unit test Next.js dynamic components?
Let's assume we have a component like this (using a dynamic import): import dynamic from 'next/dynamic'; const ReactSelectNoSSR = dynamic(() ...
Read more >
Dynamically Importing Components with React.lazy
In React, dynamically importing a component is easy—you invoke React.lazy with the standard dynamic import syntax and specify a fallback UI.
Read more >
import - JavaScript - MDN Web Docs - Mozilla
To load modules in non-module contexts, use the dynamic import ... The importing module can only read the value but can't re-assign it....
Read more >
Dynamic imports and code splitting with Next.js
It was developed as an upgrade to static imports in JavaScript, which is the standard way of adding imports for modules or components...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found