简体   繁体   中英

Next.js + Jest moduleNameMapper without TypeScript

I am struggling to get moduleNameMapper to work with NextJS / JavaScript. For this project we are not using TypeScript.

  • Next: 12.2.5
  • React: 18.2.0
  • Jest: 29.0.1
  • Jest environment jsdom: 29.0.1

Here is my jsconfig.json file

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/components/*" : ["components/*"],
            "@/styles/*" : ["styles/*"],
            "@/config/*" : ["config/*"],
            "@/hooks/*" : ["hooks/*"],
            "@/store/*" : ["store/*"],
        }
    }
}

I can do the following in my project

import Layout from "@/components/Layout"
import useFetch from "@/hooks/fetch"

However, when I try to test I get this message Cannot find module @/hooks/fetch from pages/account/login/index.js

Here is my jest.config.js file

const nextJest = require('next/jest');

const createJestConfig = nextJest({
    dir: "./",
});
const customJestConfig = {
    moduleDirectories: ["node_modules", "<rootDir>"],
    moduleNameMapper: {
        "^@/hooks/*": "/hooks/*"
    },
    testEnvironment: "jest-environment-jsdom",
}
module.exports = createJestConfig(customJestConfig)

As you can see I am trying to map the paths in moduleNameMapper but this still isn't working. How do I correct this?

I am hoping to use the same import formatting for both project and test project

many thanks

Managed to resolve this by changing the jsconfig.js file

const nextJest = require('next/jest');

const customJestConfig = {
    moduleDirectories: ["node_modules", "<rootDir>"],
    testEnvironment: "jest-environment-jsdom",
};

const createJestConfig = nextJest({
  dir: './',
})(customJestConfig);

module.exports = async () => 
{
  // Create Next.js jest configuration presets
  const jestConfig = await createJestConfig();

  // Custom `moduleNameMapper` configuration
  const moduleNameMapper = {
    ...jestConfig.moduleNameMapper,
    '^@/(.*)$': '<rootDir>/$1',
  };

  return { ...jestConfig, moduleNameMapper };
};

Source: https://github.com/vercel/next.js/issues/36682

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM