Next.js Discord

Discord Forum

how to test next-js dynamic import component with jest?

Unanswered
Harlequin posted this in #help-forum
Open in Discord
HarlequinOP
i want to test dynamic import component with jest, but every time i get error " Unable to find an element", i have tried to mock dynamic import with different ways, and also tried to increase test time out but nothing works for me yet.

11 Replies

HarlequinOP
@Northeast Congo Lion
@"use php" @Cinnamon @Atlantic cod @Morelet’s Crocodile
Northeast Congo Lion
Why me?
@Northeast Congo Lion Why me?
HarlequinOP
you look like expert
Weevil parasitoid
@Harlequin share your jest.config.ts , jest.setup.ts , package.json and tsconfig.json
@Weevil parasitoid <@681493418249420814> share your jest.config.ts , jest.setup.ts , package.json and tsconfig.json
HarlequinOP
jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  testTimeout: 30000,
  bail: false,
  preset: "ts-jest",
  testEnvironment: "jsdom",
  transform: {
    "^.+\\.tsx?$": [
      "ts-jest",
      {
        tsconfig: "tsconfig.jest.json",
        isolatedModules: true,
      },
    ],
  },
  setupFilesAfterEnv: ["./jest.setup.ts"],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    "swiper/css": "swiper/swiper.min.css",
    "\\.(svg|jpg|jpeg|png|gif|css|less)$": "identity-obj-proxy",
  },
  transformIgnorePatterns: ["node_modules/(?!swiper|ssr-window|dom7)"],
};

const dotenv = require("dotenv");
dotenv.config({ path: "./.env.development" });

jest.setup.ts
import '@testing-library/jest-dom'
jest.mock('next/dynamic', () => () => {
    const DynamicComponent = () => null;
    DynamicComponent.displayName = 'LoadableComponent';
    DynamicComponent.preload = jest.fn();
    return DynamicComponent;
});
HarlequinOP
@Weevil parasitoid any recommendations?
@Harlequin i want to test dynamic import component with jest, but every time i get error " Unable to find an element", i have tried to mock dynamic import with different ways, and also tried to increase test time out but nothing works for me yet.
Just want to make sure you dont make a habit of tagging people without explicit permission. This is not a paid service and there is no expectation of assistance.