nestJS / 'cannot find module' when test

flobeeee·2021년 6월 3일
3

시행착오

목록 보기
13/43
post-thumbnail

문제발생

npm run test:watch 하니까 해당 에러 발생

API 서버 구현하고, insomnia 로 돌려서 확인까지 다 했는데
page model 이 모듈이 없다니..
8번코드 주석처리하니까
9번도 모듈이 없다고 뜬다.

시도

TypeScript 사용할 때 'Cannot find module ...' 에러 참고해서

적용해봤으나 같은 에러 발생해서.
VSC 껐다 켜봤으나 동일.

해결

Jest + Typescript + Absolute paths (baseUrl) gives error: Cannot find module

답변들을 하나하나 적용해보다가 찾아냈다!

답변댓글을 보면 nestjs framework 에 잘 적용된다고 되어있다.

// package.json
// 변경 전
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir":"src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node",
    "moduleDirectories": ["node_modules", "src"]
  }
// 변경 후
  "jest": {
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "roots": [
      "src"
    ],
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node",
    "moduleNameMapper": {
      "src/(.*)": "<rootDir>/src/$1"
    }
  }

결과

잘 돌아간다!
전후 코드를 보면, 자잘하게 변경된 걸 알 수 있다.


셋팅이 제일 어려운 것 같다.

profile
기록하는 백엔드 개발자

1개의 댓글

comment-user-thumbnail
2021년 8월 12일

삽질 공유 감사합니다! 저는 도저히 위 방법으로 어떻게 안 되길래 vscode/typescript 설정에서 auto import 할 때 상대적경로로 import하게 변경해주는 방법으로 해결했어요!

답글 달기