src/components/Header/MainHeader.test.tsx
● 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:
/Users/jiheon/for-dogs-services/src/assets/main-logo.svg:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
^
SyntaxError: Unexpected token '<'
9 | import useAuth from "@/hooks/useAuth";
10 |
> 11 | import mainlogo from "@/assets/main-logo.svg";
| ^
12 | import mainother from "@/assets/mainother.svg";
13 | import basket from "@/assets/basket-buy-cart.svg";
14 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14)
at Object.<anonymous> (src/components/Header/MainHeader.tsx:11:1)
at Object.<anonymous> (src/components/Header/MainHeader.test.tsx:6:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.668 s
Ran all test suites.
해당 오류는 Jest가 SVG 파일을 처리하지 못해서 발생하는 문제이며 Jest는 기본적으로 JavaScript 파일만 처리하도록 설정되어 있으며, SVG와 같은 비코드 파일들은 Jest가 파싱할 수 없기 때문에 오류가 발생합니다.
해결 방법:
1. npm install jest-transformer-svg --save-dev
(jest-svg-transformer는 jest 27까지만 지원하는 버전이다. jest 28 이상부터는 반드시 jest-transformer-svg를 사용하여야 한다. (jest가 27 -> 28로 업데이트 되면서 transformer의 process와 processAsync 메서드가 string이 아닌 { code: string } 형태의 객체를 반환하도록 변하였기 때문입니다.))
jest.config.ts에 해당 내용을 추가해주고
\moduleNameMapper: {
"^.+\\.svg$": "jest-transformer-svg", // SVG 파일 매핑
},
transform: {
"^.+\\.svg$": "jest-transformer-svg", // SVG 변환 추가
},
Vite와 같은 최신 JavaScript 빌드 도구는 ES 모듈을 기본으로 사용하고, Jest도 ESNext 모듈을 지원하기 때문에, 이 설정을 통해 모듈 시스템 간의 호환성을 높이기 위해 tsconfig.json에 module을 "ESNext"로 변경해줍니다.
Vite와 Jest의 호환성이 안 좋기 때문에 Vite를 사용할 때는 Vitest를 사용하는 것을 권장합니다.