Jest setup with typescript

Falcon·2022년 4월 5일
2

javascript

목록 보기
14/28

이 글의 대상

Node.js + Typescript + Jest 세팅이 필요한 사람

시간이 없다면

다음 repository 를 클론해서 쓰시라.

Step by Step

1. 필요한 패키지 모두 설치

  • @types/jest
    ⚠️ 얼핏 보면 typescript 에만 필요할 것 같지만 javascript 에서도 describe(), expect() 등의 메소드를 IDE 에서 인식하게 하려면 이 패키지를 설치해야한다.
  • jest
  • ts-jest
  • typescript
# typescript 지원
$ yarn add -D jest @types/jest ts-jest typescript

# javascript 지원
$ yarn add -D jest @types/jest

2. jest.config.js 파일 설정

module.exports = {
  // ts-jest 사용
    preset: "ts-jest",
    // https://github.com/facebook/jest/issues/3613

  // ⭐️ 프로젝트 루트 디렉토리 상대경로
  // 여기서 삽질하기 쉬운데, jest.config.js 파일로부터 
  // 루트 디렉토리까지의 상대경로를 입력해주면 됨.
  
    rootDir: '..',
  // 테스트 대상 파일 정규식
    testMatch: [
        "**/?(*)+(test).ts"
    ],
    testEnvironment: "node",
    resetMocks: true,
    clearMocks: true,
  
  // 💡 tsconfig 에서 `baseUrl` 과 `paths` 를 사용하는 경우 필요
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
        // rootDir is the root of the directory containing `jest config file` or the `package.json`
        prefix: '<rootDir>'
    })
}

(Optional) Absolute paths in typescript

타입스크립트에서 다음과 같이 커스터마이징한 절대경로를 사용하려면 tsconfig-paths 모듈이 필요하다.

import {Book} from "@models/Book";
import {bookController} from '@controllers/Book";

따라서 해당 패키지도 설치하고 tsconfig.json 도 다음과 같이 설정해야한다.

# 패키지 설치
$ yarn add -D tsconfig-paths

tsconfig.json


// 중략..

  "ts-node": {
    "transpileOnly": true,
    "require": ["tsconfig-paths/register"]
  },
  "compilerOptions": {
    // 프로젝트 루트 경로
    "baseUrl": ".",
    // path alias 지정
    "paths": {
      "@models/*"       : ["src/models/*"],
      "@controllers/*"  : ["src/controllers/*"],
    },
  }
// 중략..

3. package.json 설정

💡 위에서 설정한 파일의 옵션에 따라 jest 를 실행하도록 스크립트 등록

{
  // ...
    "scripts": {
	// jest.config.js 로 jest 실행
    "test": "jest -c test/jest.config.js"
  },
  //...

4. 실행

$ yarn run test

편-안


coverage 는 무엇인가요?

테스트 결과 분석 리포트로 보통 html 파일 형태로 제공된다.

🔗 Reference

profile
I'm still hungry

0개의 댓글