繁体   English   中英

Next.js + Jest moduleNameMapper 没有 TypeScript

[英]Next.js + Jest moduleNameMapper without TypeScript

我正在努力让moduleNameMapper与 NextJS / JavaScript 一起工作。 对于这个项目,我们没有使用 TypeScript。

  • 下一个:12.2.5
  • 反应:18.2.0
  • 开玩笑:29.0.1
  • Jest 环境 jsdom:29.0.1

这是我的jsconfig.json文件

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

我可以在我的项目中执行以下操作

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

但是,当我尝试测试时,我收到此消息Cannot find module @/hooks/fetch from pages/account/login/index.js

这是我的jest.config.js文件

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)

如您所见,我正在尝试 map moduleNameMapper中的路径,但这仍然无法正常工作。 我该如何纠正?

我希望对项目和测试项目使用相同的导入格式

非常感谢

设法通过更改jsconfig.js文件来解决此问题

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 };
};

来源: https://github.com/vercel/next.js/issues/36682

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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