FrontEnd/Vue

[vue3/jest] 🚫에러 일지 - Jest encountered an unexpected token

Grace 2023. 2. 7. 14:35

react, next에 찌든 뇌를 세탁해서 더 넓은 시야로 프로젝트를 보기 위해 요즘 vue3를 공부하면서 프로젝트를 진행 중입니다.
어느정도 프로젝트가 완성되고 unit 테스트를 위해 jest를 연결 중인데 계속 해서 에러가 나서 이틀 정도 고생했던 것 같습니다.
다른 분들이 저와 같은 문제로 너무 오랜 기간 고민하지 않으셨으면 하는 바램에서 에러 일지를 작성합니다

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

먼저 에러 메세지가 너무 길게 나와서 당황하셨을텐데!!!!
메세지가 긴 것에 비해 해결 방법은 간단합니다. 먼저 어떤 에러인지 살펴보겠습니다.
jest가 파일을 parse하는데 실패했는데 아마도 syntax 에러인 것 같다고 하네요 !
babel 얘기가 많이 나오는 것을 보니, babel에서 parse 하려고 했는데 잘 안됐나봐요
transformer에 의해 node_modules 폴더가 기본적으로 무시되고 있고, 그 아래로 쭉 해결 방법에 대해 추천해주고 있네요!

    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.

1. 먼저 ECMAScript 모듈을 사용하려고 하는거라면 해당 주소를 참조하라고 하는데, 해당 주소로 들어가서 읽어보면 module에서 가져온 메서드? 함수 같은 것들을 사용하기 위해 모의 함수(jest.fn())을 사용하라는 등의 추천을 해줍니다.
저는 이미 이 과정을 적용시켜줬기 때문에 다음으로 넘어갑니다.

2. typescript를 사용하고 있다면 해당 주소를 참조하라고 하는데, 저는 타입스크립트는 아직 적용하지 않아서 이 부분도 그냥 넘어갔습니다.

3. 만약 node_modules 안의 일부 파일을 변환하려면 config에서 transformIgnorePatterns를 지정할 수 있다고 합니다. jest.config.js를 확인해볼게요!

module.exports = {
    // 파일 확장자를 지정하지 않은 경우, Jest가 검색할 확장자 목록
    moduleFileExtensions: [
        'js',
        'vue'
    ],
    // ~ 같은 경로 별칭을 매핑
    // <rootDir> 토큰을 사용해 루트 경로 참조
    moduleNameMapper: {
        '~/(.*)$': '<rootDir>/src/$1'
    },
    // 일치하는 경로에서는 모듈을 가져오지 않습니다.
    modulePathIgnorePatterns: [
        '<rootDir>/node_modules/',
        '<rootDir>/dist'
    ],
    // jsdom 환경에 대한 URL 설정
    testURL: 'http://localhost',
    // 정규식과 일치하는 파일의 변환 모듈 지정
    transform: {
        '^.+\\.vue$': 'vue3-jest',
        '^.+\\.js$': 'babel-jest'
    }
}

앗 확인해보니 transformIgnorePatterns는 지정되어 있지 않네요! modulePathIgnore로 모듈을 가져오고 있지 않은데 제가 테스트 안쪽에서 axios 모듈 등을 가져오고 있어서 문제가 되는 것 같습니다.
저는 해당 파일에 transformIgnorePatterns를 추가해주었습니다.

module.exports = {
...
transformIgnorePatterns: [`/node_modules/(?!axios)`],
}

여러분들은 axios 자리에서 여러분이 가져오지 못하는 모듈의 이름을 넣어주시면 됩니다! 쉼표로 구분하여 가져오고 싶은 모듈을 더 추가하실 수도 있습니다!

이렇게 해서 다시 실행하면 에러가 사라집니다!
(하지만 저는 다른 에러가 발생해서 이 에러 또한 핸들링을 해주었습니다... 다음 게시글에서 가져오겠습니다.)

추가적으로 논의할 사항이나 질문, 피드백 모두 편하게 댓글 달아주세요!