1

I know this issue has been raised a few times but I've tried every solution I can find on stack overflow with no joy. My path aliasing works fine in terms of rendering content, but when I try to run a test, it says Cannot find module '@/components' from '__tests__/who-we-are.test.js'. Please note I am using an index file to export all my components from the component folder.

jsconfig.json:

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

jest.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 }
}

test file:

import { WhoWeAreComponent } from '@/components'

I have tried changing the alias paths in both the jsconfig.json and the jest.config.json. I also tried adding a webpack.shared.js file as per some of the other solutions - it had no effect. The only thing that appears to make the test run is importing the component into the test file without using aliasing, i.e. import WhoWeAreComponent from '../components/who-we-are-section/who-we-are.component'

TIA!

0 Answers0