Jest 测试失败:SyntaxError: Unexpected token < [英] Jest test fail: SyntaxError: Unexpected token <
问题描述
不知道去哪里寻找这个错误.
Not sure where to look for this error.
将 Typescript 与 React、Jest 和 Enzyme 结合使用进行单元测试.
Using Typescript with React, and Jest and Enzyme for unit testing.
Package.json 示例:
Package.json sample:
"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 测试结果:
Running npm test results in:
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 时忽略抛出这个错误?
It appears to be happening the first place where i use require
to load a static .svg
file. Why can it not handle that? Is there a way to ignore throwing this error when using require?
推荐答案
Jest 不使用 Webpack,因此它不知道如何加载 js/jsx 以外的其他文件扩展名.要添加对其他扩展的支持,您需要编写自定义转换器.其中一个转换器是您在此片段的配置中定义的 Typescript 转换器:
Jest doesn't use Webpack so it doesn't know how to load other file extensions than js/jsx. To add support for other extensions you need to write custom transformers. One of the transformers is a Typescript transformer which you have defined in your configuration in this fragment:
"transform": {
"^.+\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
现在您需要为 svg 文件添加转换器.让我们扩展你的笑话配置
Now you need to add transformer for svg files. Let's extend your jest config
"transform": {
"^.+\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"^.+\.svg$": "<rootDir>/svgTransform.js"
},
并在您的根目录中创建具有以下内容的 svgTransform.js 文件
and create the svgTransform.js file in your root directory with the following content
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'svgTransform';
},
};
当然,这是一个返回相同值的基本转换器.
Of course, it's a basic transformer that returns always the same value.
文档链接:http://facebook.github.io/jest/docs/en/configuration.html#transform-object-string-string
这篇关于Jest 测试失败:SyntaxError: Unexpected token <的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!