Search code examples
typescriptunit-testingnext.jsconfigts-jest

jest config - Cannot find module


I dont fully understand config files but having following issues when trying run jest unit test:

 Cannot find module '@/app/utils/regex' from 'src/_components/DriverSearchForm.tsx'

My jest.config

    import type { Config } from 'jest'
import nextJest from 'next/jest.js'

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

const config: Config = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleDirectories: ['node_modules', '<rootDir>/src'],
  moduleNameMapper: {
    '^@/_components/(.*)': '<rootDir>/src/_components/$1',
  },
  testEnvironment: 'jsdom',
  preset: 'ts-jest',
  transform: {
    '^.+\\.(js|jsx|ts|tsx|mjs)$': ['ts-jest', { tsconfig: 'tsconfig.test.json' }],
  },
}

export default createJestConfig(config)

Solution

  • The key is the alias of the module name, the value is the target module you want to map to. When you import from @/app/utils/regex, it will be mapped to the <rootDir>/app/utils/regex module.

    <rootDir>/jest.config.js:

    moduleNameMapper: {
        '^@/app/(.*)': '<rootDir>/app/$1',
    }
    

    <rootDir>/tsconfig.json:

    "paths": {
      "@/app/*": [
        "app/*"
      ]
    }
    

    <rootDir>/app/utils/regex.ts:

    export const regex = /test/i
    

    index.ts:

    import { regex } from '@/app/utils/regex';
    
    console.log(regex);
    

    index.test.ts:

    import './';
    
    describe('78224123', () => {
      test('should pass', () => {
        expect(1 + 1).toEqual(2);
      });
    });
    

    Test result:

      console.log
        /test/i
    
          at Object.log (stackoverflow/78224123/index.ts:3:9)
    
     PASS  stackoverflow/78224123/index.test.ts (7.62 s)
      78224123
        √ should pass (2 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        18.59 s