Jest

JEST - 기본설정

training center 2021. 5. 23. 21:02

포스팅 목적: FrontEnd test 도입 

 

1) 설치 및 실행

설치 방법

yarn add --dev jest

or

npm install --save-dev jest

 

설치 후 Package.json에 설정해야 할 것

{
  "scripts": {
    "test": "jest"
  }
}

yarn test or npm run test 명령으로 테스트를 실행할 수 있다.

 

2) 추가 구성

프로젝트에서 Babel을 사용할 경우 jest에도 Babel 설정이 필요하다.

yarn add --dev babel-jest @babel/core @babel/preset-env

babel.config.js에 설정해야 할 것

// babel.config.js
module.exports = {
  presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};

 

jest는 Babel을 통해 TypeScript를 지원한다.

yarn add --dev @babel/preset-typescript

설치후 babel.config.js에 설정해야 할 것

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', {targets: {node: 'current'}}],
+    '@babel/preset-typescript',
  ],
};

 

3) 발생할 수 있는 에러

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

와 같은 에러가 발생한다면,

jest.config 와 babel.config가 설정되었는지 확인하자

 

jest.config

const config = {
  moduleFileExtensions: ["js", "json", "jsx", "ts", "tsx", "json"],
  transform: {
    "^.+\\.(js|jsx)?$": "babel-jest",
  },
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/$1",
    '\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/__mocks__/fileMock.js',
    '\\.(css|less)$': '<rootDir>/__mocks__/fileMock.js',
  },
};

module.exports = config;

babel.config

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          node: "current",
        },
      },
    ],
  ],
};

'Jest' 카테고리의 다른 글

JEST - Expect API (1)  (0) 2021.05.29