【问题标题】:Path aliasing not working with Next/React/Jest tests路径别名不适用于 Next/React/Jest 测试
【发布时间】:2023-02-21 19:50:15
【问题描述】:

我知道这个问题已经被提出过几次,但我已经尝试了所有我能在堆栈溢出上找到的解决方案,但没有任何乐趣。我的路径别名在呈现内容方面工作正常,但当我尝试运行测试时,它显示 Cannot find module '@/components' from '__tests__/who-we-are.test.js'。请注意,我正在使用索引文件从组件文件夹中导出所有组件。

jsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["./components/*"]
    }
  }
}

开玩笑.config.js:

const nextJest = require('next/jest')

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

const createJestConfig = nextJest({
  dir: './',
  collectCoverage: true,
  coverageProvider: 'v8',
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
    '!<rootDir>/out/**',
    '!<rootDir>/.next/**',
    '!<rootDir>/*.config.js',
    '!<rootDir>/coverage/**',
  ],
  moduleNameMapper: {
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
    '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
    '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/__mocks__/fileMock.js`,
    '^@/components/(.*)$': '<rootDir>/components/$1',
  },
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  testEnvironment: 'jest-environment-jsdom',
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
  },
  transformIgnorePatterns: [
    '/node_modules/(?!swiper|@swiper)',
    '^.+\\.module\\.(css|sass|scss)$',
  ],
})(customJestConfig)

module.exports = async () => {
  const jestConfig = await createJestConfig()

  return { ...jestConfig }
}

测试文件:

import { WhoWeAreComponent } from '@/components'

我尝试更改jsconfig.jsonjest.config.json 中的别名路径。我还尝试根据其他一些解决方案添加 webpack.shared.js 文件 - 它没有效果。唯一使测试运行似乎是在不使用别名的情况下将组件导入测试文件,即import WhoWeAreComponent from '../components/who-we-are-section/who-we-are.component'

TIA!

【问题讨论】:

    标签: reactjs next.js jestjs alias


    【解决方案1】:

    您是否在 jsconfig.json 中缺少相对路径前缀?

    "@/components/*": ["./src/components/*"]

    【讨论】:

    • 感谢您的回答 - 我的组件文件夹位于项目的根目录中。因此,将 baseURL 设置为“.”我觉得应该可以吧?
    • 试一试?我将 baseURL 设置为 .,但还在我的路径前加上 ./。你的玩笑 moduleName 语法是正确的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 2020-09-13
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多