[에러 해결] Jest encountered an unexpected token

지은·2023년 8월 7일
0

에러 해결

목록 보기
7/7

CRA로 만든 리액트 앱에서 간단한 테스트코드를 작성하고 npm run test 명령어를 입력했는데, 다음과 같은 에러가 발생했다.

에러 로그

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:

    /Users/jieunchun/jest-login-test/node_modules/axios/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                      ^^^^^^

해석) Jest가 예상치 못한 토큰을 발견했습니다.

  • Jest가 파일을 구문 분석(parse)하지 못했습니다.
    e.g. 코드 또는 종속성이 비표준 자바스크립트 구문을 사용하거나 Jest가 이러한 구문을 지원하도록 구성되지 않은 경우에 발생합니다.
  • Jest는 Babel을 지원하며, Babel 구성에 따라 파일을 유효한 JS로 변환하는 데 사용됩니다.
  • 기본적으로 "node_modules" 폴더는 변환기에서 무시됩니다.

에러 발생한 곳

SyntaxError: Cannot use import statement outside a module

    > 1 | import axios from 'axios';
        | ^
      2 | import { useState } from 'react';
      3 |
      4 | const Login = () => {

해석) Syntax Error : 모듈 외부에서 import 문을 사용할 수 없습니다.

원인

이 에러는 Jest가 코드의 import문을 해석하지 못해서 발생한 것이다.
테스트하려는 JavaScript 파일은 ES6 문법을 사용하고 있는데, Node.js 환경에서는 기본적으로 ES6 문법을 지원하지 않기 때문에, Jest를 사용하여 테스트하려는 파일이나 코드가 ES6 문법을 사용하고 있다면 추가적인 구성(configuration)이 필요하다.
따라서 Babel을 사용해서 코드를 변환하고, Jest 구성에서 ES6 모듈을 지원하도록 설정해야 한다.


해결 방법

시도 1

해결하기 위해서 아래 방법을 시도해봤으나 실패..

1. 추가 종속성 설치

npm install @babel/core @babel/preset-env @babel/preset-react babel-jest --save-dev

2. babel 설정 파일 작성

// babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react']

};

3. jest 설정 파일 작성

// jest.config.js
module.exports = {
	moduleFileExtensions: ['js', 'jsx'],
	transform: {
		'^.+\\.(js|jsx)$': 'babel-jest',
	},
	transformIgnorePatterns: ['/node_modules/(?!(axios)/)'],
};

시도 2

package.json 파일의 test 명령어에 다음과 같은 옵션을 적용한다.

"scripts": {
    //..configs
    "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",
  },

--transformIgnorePatterns은 Jest가 파일을 변환할 때 무시할 파일의 패턴을 설정하는 옵션이다.

참고 : Updating Axios from 0.27.2 to 1.0.0 breaks Jest tests in a create-react-app app #5026

이 방법은 일시적인 조치라고 하는데, 일단은 해결 방법을 더 찾아봐야겠다..😢

profile
블로그 이전 -> https://janechun.tistory.com

1개의 댓글

comment-user-thumbnail
2023년 8월 13일

Jest 가 Node환경에서 작동하기 때문에 esm 문법을 실행시키지 못하는군요. 찾아보니 공식적으로 esm을 사용하도록 하는 방법이 애매한 것 같네요ㅠㅠ 도움이 되었습니다!

답글 달기