jest 테스트 시 절대경로 에러 발생 이슈

박진(TsTunas)·2023년 2월 27일
0

jest 세팅

# package.json
{
  ...,
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

에러 발생 메시지

Cannot find module 'src/collections/entities/collection.entity' from 'auth/entities/user.entity.ts'

    Require stack:
      auth/entities/user.entity.ts
      auth/auth.service.ts
      auth/auth.controller.ts
      auth/auth.controller.spec.ts

    > 1 | import { Collection } from 'src/collections/entities/collection.entity';        | ^
      2 | import { Photospot } from 'src/collections/entities/photospot.entity';  
      3 | import { Join } from 'src/meetups/entities/join.entity';
      4 | import { Meetup } from 'src/meetups/entities/meetup.entity';

      at Resolver._throwModNotFoundError (../node_modules/jest-resolve/build/resolver.js:427:11)
      at Object.<anonymous> (auth/entities/user.entity.ts:1:1)
      at Object.<anonymous> (auth/auth.service.ts:4:1)
      at Object.<anonymous> (auth/auth.controller.ts:2:1)
      at Object.<anonymous> (auth/auth.controller.spec.ts:2:1)

에러 발생 이유

테스트 환경으로 코드를 실행할 때에 src 경로로 쓰여진 절대 경로를 해석하질 못 하기 때문이다. jest config를 수정해줘야한다.

에러 해결

# package.json
 "jest": {
    ...,
    "moduleNameMapper": {
      "src/(.*)": "<rootDir>/$1"
    }
  }

src로 시작하는 절대 경로를<rootDir>를 이용하여 매핑해주는 설정을 넣어주면 된다.

이후 생각할 부분

  • vscode의 jest extension으로 돌리면 기존 에러가 계속 나타난다. jest를 실행하여 돌렸을 때와 무슨 차이가 있는지 생각해볼 필요가 있다.
profile
자바스크립트 전문가가 되고 싶은 아마추어

0개의 댓글