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",
- 다음과 같은 방법으로 SVG를 조롱합니다.
__mocks__/svgMock.js
파일:
import React from "react";
export default "SvgURL";
export const ReactComponent = ({ width, height }) => (
<div>
w-{width} h-{height}
</div>
);
- 다음 속성을 사용하여 jeast.config.js를 변경하여 이 SVG 모커의 위치를 Jeest에 알립니다.
moduleNameMapper: {
"\\.svg": "<rootDir>/__mocks__/svgMock.js",
},
언급URL : https://stackoverflow.com/questions/46791263/jest-svg-require-causes-syntaxerror-unexpected-token
'sourcetip' 카테고리의 다른 글
에서 .에서 .에서 . (0) | 2023.03.09 |
---|---|
파이프 구분 키 및 bash 값에서 jq를 사용하여 JSON 생성 (0) | 2023.03.09 |
webpack-cli에서 오류 발생: 웹 팩 구성에서 "TypeError: merge is not function" (0) | 2023.03.09 |
AngularJS에서는 한 페이지에 있는 모든 스코프를 어떻게 찾을 수 있습니까? (0) | 2023.03.09 |
$(표준)웹 페이지를 떠나기 전에 AJAX 호출이 완료될 때까지 언로드 대기 (0) | 2023.03.09 |