sourcetip

Jest: SVG 요구 원인 "SyntaxError:예기치 않은 토큰 <"

fileupload 2023. 3. 9. 22:16
반응형

Jest: SVG 요구 원인 "SyntaxError:예기치 않은 토큰 <"

이 에러가 발생하는 장소를 알 수 없습니다.

단위 테스트에 Typescript with React, Jest 및 효소를 사용합니다.

패키지json 샘플:

"scripts": {
    "start": "node server.js",
    "bundle": "cross-env NODE_ENV=production webpack -p",
    "test": "jest"
  },
  "jest": {
    "transform": {
      "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "json"
    ]
  }

npm 테스트를 실행하면 다음과 같은 결과가 됩니다.

FAIL src/components/Component.test.tsx

 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<?xml version="1.0" encoding="UTF-8"?>
                                                                                             ^

    SyntaxError: Unexpected token <

편집: 처음 사용하는 곳에서 발생하는 것 같습니다.require정전기를 장전하다.svg왜 그걸 처리하지 못하는 거죠?require를 사용할 때 이 오류를 발생시키는 것을 무시할 수 있는 방법이 있습니까?

Jest는 웹 팩을 사용하지 않기 때문에 js/jsx 이외의 파일 확장자를 로드할 수 없습니다.다른 확장에 대한 지원을 추가하려면 사용자 정의 변압기를 작성해야 합니다.트랜스 중 하나는 이 fragment의 Configuration에서 정의한 Typescript 트랜스입니다.

"transform": {
   "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},

이제 svg 파일용 트랜스포머를 추가해야 합니다.농담 설정을 확장합니다.

"transform": {
       "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js",
       "^.+\\.svg$": "<rootDir>/svgTransform.js" 
    },

루트 디렉토리에 다음 내용으로 svgTransform.js 파일을 만듭니다.

module.exports = {
  process() {
    return { code: 'module.exports = {};' };
  },
  getCacheKey() {
    // The output is always the same.
    return 'svgTransform';
  },
};

물론 항상 같은 값을 반환하는 기본 변압기입니다.

매뉴얼 링크:http://facebook.github.io/jest/docs/en/configuration.html#transform-object-string-string

@svgr/webpack 모듈을 사용하여 웹 팩이 svgs Import를 처리할 수 있는 경우 @svgr을 사용한 테스트 처리 방법을 설명하는 페이지가 나타납니다.여기 있습니다

후세를 위해 복사했습니다.

/__mocks__/svgrMock.js

import * as React from 'react'
export default 'SvgrURL'
export const ReactComponent = 'div'

package.json

"jest": {
  "moduleNameMapper": {
    "\\.svg": "<rootDir>/__mocks__/svgrMock.js"
  }
}

npm 패키지를 사용할 수 있습니다.jest-transform-stub

Jest 설정 파일에서 다음과 같은 변환을 추가합니다.

"transform": {
  ...
  "^.+\\.svg$": "jest-transform-stub",
  ...
}

Same transform can be use for any asset file.
  ".+\\.(css|less|sass|scss|png|jpg|gif|ttf|woff|woff2|svg)$": "jest-transform-stub",

  1. 다음과 같은 방법으로 SVG를 조롱합니다.__mocks__/svgMock.js파일:
import React from "react";
export default "SvgURL";
export const ReactComponent = ({ width, height }) => (
  <div>
    w-{width} h-{height}
  </div>
);
  1. 다음 속성을 사용하여 jeast.config.js를 변경하여 이 SVG 모커의 위치를 Jeest에 알립니다.
  moduleNameMapper: {
    "\\.svg": "<rootDir>/__mocks__/svgMock.js",
  },

언급URL : https://stackoverflow.com/questions/46791263/jest-svg-require-causes-syntaxerror-unexpected-token

반응형