Jest ESModules 설정 방법

최소희·2024년 5월 29일
0

프론트엔드 학습

목록 보기
16/23
post-thumbnail

상황

Jest로 테스트 코드를 돌리는데, axios import 구문을 마주하여 다음 에러가 발생하였다.

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:
                                                                         ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import axios from "axios";
        | ^
      2 | import { BASE_URL } from "../constants/url";
      3 |
      4 | const axiosInstance = axios.create({

원인 분석

Jest가 axios 모듈을 ESModules로 처리하지 못하기 때문이다. Jest는 기본적으로 CommonJS 모듈을 사용하며, ESModules를 사용하기 위해서는 추가적인 설정이 필요하다.

해결 방법

Jest가 axios 모듈을 ESModules로 처리하지 못해 발생하는 문제를 해결하려면 Jest와 Babel의 설정을 적절히 구성해야 한다.

1.Jest 설정 파일 구성 (jest.config.js) 설정

Jest가 ESModules를 지원하도록 설정을 변경한다.

jest.config.js 파일을 생성하거나 기존 파일을 다음과 같이 수정한다.

과거에는 globals 섹션에 ts-jest 설정을 넣었지만, 최신 ts-jest 버전 기준으로는 transform 섹션 안에 넣어야 한다.

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: "ts-jest/presets/default-esm", // ESM 지원을 위한 ts-jest 프리셋
  transformIgnorePatterns: [
    "/node_modules/(?!axios/)", // axios 모듈을 변환 대상에 포함
  ],
  moduleNameMapper: {
    "^(\\.{1,2}/.*)\\.js$": "$1", // ESM 경로 문제 해결
  },
  transform: {
    "^.+\\.tsx?$": [
      "ts-jest",
      {
        useESM: true, // ESM 사용 설정 (global이 아닌 transaform 내 설정)
      },
    ],
  },
  extensionsToTreatAsEsm: [".ts", ".tsx"], // ESM으로 처리할 확장자 목록
};

2. Babel 설정 파일 (babel.config.js) 추가

Jest가 ESModules를 처리할 수 있도록 Babel 설정 파일을 루트 디렉토리에 추가한다.

Babel을 사용해 EsModules와 TypeScript 코드를 트랜스파일 할 수 있도록 설정한다.

module.exports = {
  presets: [
    "@babel/preset-env", // 최신 JavaScript를 ES5로 변환
    "@babel/preset-typescript", // TypeScript 지원
  ],
};

3. 패키지 설치

설정을 적용하기 위해 필요한 패키지를 설치한다.

yarn add --save-dev ts-jest @types/jest jest @babel/preset-env @babel/preset-typescript babel-jest

참고 자료
Jest-ECMAScript Modules
ts-jest

profile
프론트엔드 개발자 👩🏻‍💻

0개의 댓글