본문으로 바로가기

jestjs.io/docs/en/configuration

 

Jest · 🃏 Delightful JavaScript Testing

🃏 Delightful JavaScript Testing

jestjs.io

 

jest.config.js/ts 혹은 package.json 내부에 "jest"를 정의함으로서 jest를 구성할 수 있다.

Nest에서는 package.json을 확인해보면 jest 세팅은 다음과 같이 되어 있다.

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

 

여기에는 많은 옵션들이 존재하지만, 기본적으로 사용된 옵션을 위주로 알아보자.

 

 

- moduleFileExtensions 

jestjs.io/docs/en/configuration#modulefileextensions-arraystring

Default: ["js", "json", "jsx", "ts", "tsx", "node"]

 

여러분들이 작성한 모듈의 확장자를 배열로 적어주면 된다. 가장 자주 사용되는 확장자부터 차례대로 적어주면 된다. 만약 TS를 주로 사용하는 프로젝트라면 ts, tsx를 먼저 위치시켜주면 된다.

Nest에서는 allowJS를 켜고 사용하는 사람의 편의성 때문인지 js, json, ts 순으로 배치했다.

일반적인 프로젝트에서는 굳이 건드릴 필요는 없다.

 

 

- rootDir

jestjs.io/docs/en/configuration#rootdir-string

Default: Jest config file이 있는 경로 혹은 package.json이 있는 경로. 둘 다 존재하지 않는다면 현재 경로를 rootDir로 설정함.

 

프로젝트 구조에 따라 종종 src나 lib와 같은 다른 경로를 rootDir로 지정하고 싶다면 적어주면 된다. 여튼 진입점을 적어주면 된다. Nest에서는 비즈니스 로직이 존재하는 코드가 전부 ./src이다.

 

 

- testRegex 

The pattern or patterns Jest uses to detect test files.

__tests__ 폴더 내에 있는 모든 것, *.(spec|test).(js|ts) 형식인 모든 파일을 test 대상으로 여긴다. 

공식 문서에 나와있는 예시는 다음과 같다.

├── __tests__
│   └── component.spec.js # test
│   └── anything # test
├── package.json # not test
├── foo.test.js # test
├── bar.spec.jsx # test
└── component.js # not test

 

Nest에서는 "testRegex"".*\\.spec\\.ts$"이다. 이 말인 즉슨, *\spec\ts 꼴 인 모든 것을 test file로 인식하겠다는 것이다.  *tip) \\ (문자 자체의 \)

nest cli를 활용하여 작성하면 자동으로 *.spec.ts 꼴인 테스트파일이 생기기 때문에 이런 식으로 작성되어 있다. 굳이 건드릴 필요 없는 설정이다.

 

 

- testMatch 

jestjs.io/docs/en/configuration#testmatch-arraystring

 

(default: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ])

살펴보니, __tests__ 폴더 내에 있는 모든 js, ts, jsx, tsx 와 spec, test가 붙은 spec.[jt]s와 test.[jt]s를 

 

The glob patterns Jest uses to detect test files. By default it looks for .js, .jsx, .ts and .tsx files inside of __tests__ folders, as well as any files with a suffix of .test or .spec (e.g. Component.test.js or Component.spec.js). It will also find files called test.js or spec.js.

 

역시나 nest에서는 굳이 건드릴 필요 없지만, 다른 프레임웤을 사용 중이라면 자주 testRegex, testMatch 둘 중에 하나는 사용하게 될 수도 있다.

 

 

- transform

jestjs.io/docs/en/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object

Default: {"\\.[jt]sx?$": "babel-jest"}

쉽게 말해 test는 일반 로직과 분리되어 동작합니다. 때문에 babel이나 webpack으로 변환되는 과정을 따로 작성해주어야 하는데 참으로 고생스러운 일입니다. transoform은 이런 변환을 자동으로 해줍니다.

 

기본값의 정규식을 해석해보자면 \.js, \.jsx, \.ts, \.tsx인 경우 babel-jest로 변환하라는 것입니다. 물론 babel-jest 플러그인을 설치해줘야 합니다. github.com/facebook/jest/tree/master/packages/babel-jest#setup 여기서 확인해보실 수 있습니다.

 

Nest에서는 "transform": {"^.+\\.(t|j)s$""ts-jest"} 로 지정되어 있습니다. 즉, ..\.js ..\.ts (depth는 상관 없음. .+는 .이 1개 이상 존재함을 의미) 꼴인 파일을 모두 ts-jest로 transform하는 것을 의미합니다. ts-jest는 github.com/kulshekhar/ts-jest 여기를 참고합시다.

 

 

- collectCoverageFrom

jestjs.io/docs/en/configuration#collectcoveragefrom-array

Default: undefined

 

glob patterns으로 coverage 정보를 위해 수집되어야 할 파일들을 명시합니다. glob pattern에 해당하는 파일에 대한 test가 없다고 하더라도 coverage로 포함됩니다.

 

Nest에서는 "collectCoverageFrom": ["**/*.(t|j)s"] 값인데, 어느 파일이건 ts/js면 일단 coverage 범위에 넣는군요.

 

- coverageThreshold 

jestjs.io/docs/en/configuration#coveragethreshold-object

Default: undefined

 

coverage 통과 기준을 세울 수 있습니다. 특정 coverage 수치 이상을 통과하지 못한다면 경고를 해줍시다.

{
  ...
  "jest": {
    "coverageThreshold": {
      "global": {
        "branches": 50,
        "functions": 50,
        "lines": 50,
        "statements": 50
      },
      "./src/components/": {
        "branches": 40,
        "statements": 40
      },
      "./src/reducers/**/*.js": {
        "statements": 90
      },
      "./src/api/very-important-module.js": {
        "branches": 100,
        "functions": 100,
        "lines": 100,
        "statements": 100
      }
    }
  }
}

 

 

 

- coverageDirectory 

Default: undefined

The directory where Jest should output its coverage files.

Nest에서는 "coverageDirectory""../coverage" 입니다.

 

 

- testEnvironment 

jestjs.io/docs/en/configuration#testenvironment-string

Default: "jsdom"

 

테스트가 진행되는 환경입니다. 기본적으로는 jsdom, 즉, dom입니다. node에서 jest를 사용하고자 하면 nede를 적어주시면 됩니다. 당연히 Nest에서는 node입니다.

 

- moduleNameMapper

jestjs.io/docs/en/configuration#modulenamemapper-objectstring-string--arraystring

Test 대상이 되는 파일에서 사용하는 외부 모듈들, 이를테면 entity, 이미지, css 등을 불러올 경로를 지정합니다.

현재 nest 7.5.3 에서는 테스트 코드를 작성할 때 외부 모듈을 찾을 수 없다고 에러를 내서, 사용자가 적절히 구성해줄 필요가 있습니다.

 

"moduleNameMapper": {"^src/(.*)$": "<rootDir>/$1"}

 

Note: If you provide module name without boundaries ^$ it may cause hard to spot errors. E.g. relay will replace all modules which contain relay as a substring in its name: relay, react-relay and graphql-relay will all be pointed to your stub.

 

- coveragePathIgnorePatterns

jestjs.io/docs/en/configuration#coveragepathignorepatterns-arraystring

 

Default: ["/node_modules/"]

test coverage 대상에서 제외할 파일을 등록할 수 있습니다.

 

 


darren, dev blog
블로그 이미지 DarrenKwonDev 님의 블로그
VISITOR 오늘 / 전체