Jest 测试失败:SyntaxError: Unexpected token <

IT技术 reactjs typescript jestjs
2021-05-10 20:18:20

不确定在哪里查找此错误。

使用 Typescript 和 React,以及 Jest 和 Enzyme 进行单元测试。

Package.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 时忽略抛出这个错误?

2个回答

Jest 不使用 Webpack,因此它不知道如何加载 js/jsx 以外的其他文件扩展名。要添加对其他扩展的支持,您需要编写自定义转换器。其中一个转换器是您在此片段的配置中定义的 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 '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 module来允许 webpack 处理导入 svgs @svgr 提供了一个页面,该页面介绍了如何使用 Jest 处理测试。这里

为后人复制。

/__mocks__/svgrMock.js

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

package.json

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