繁体   English   中英

在 next.js 中使用 jest 导入时找不到模块错误

[英]Cannot find module error while import using jest in next.js

我正在尝试在我的 Next.js 项目中配置 Jest。 在我的测试文件中,我已经导入了我的组件,例如import { HamburgerMenu } from './HamburgerMenu.jsx' 在那个组件中,还有很多其他的导入。 其中一次是

import {
  checkValidEmail, getNumbers, getFormttedPhoneNo, validateSubscription,
} from 'helpers/utils';

当我运行测试时,它给了我以下错误(在上面的 import 语句中):

Cannot find module 'helpers/utils' from 'components/common/Smart/HamburgerMenu/HamburgerMenu.jsx'

所以这里是细节。

jest.config.js (在根目录)

module.exports = {
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
  ],
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testPathIgnorePatterns: ['/node_modules/', '/.next/'],
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest'
  },
  transformIgnorePatterns: [
    '/node_modules/',
    '^.+\\.module\\.(css|sass|scss)$',
  ],
  moduleNameMapper: {
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
  },
}

我在 ESLint 文件中添加了jest: true

babel.config.js文件(在根目录):

module.exports = {
  presets: ["next/babel"],
  plugins: [["babel-plugin-styled-components", { ssr: true }]]
};

您可以尝试添加

...
moduleDirectories: ['node_modules', '.'],
...

到你的jest.config.js

暂无
暂无

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

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