Jest测试失败:SyntaxError:意外的令牌<

cbl*_*bll 12 typescript reactjs jestjs

不知道在哪里寻找此错误.

使用带有React的Typescript,以及用于单元测试的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"
    ]
  }
Run Code Online (Sandbox Code Playgroud)

运行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 <
Run Code Online (Sandbox Code Playgroud)

编辑:它似乎发生在我require用来加载静态.svg文件的第一个地方.为什么不能处理呢?有没有办法在使用require时忽略抛出此错误?

nib*_*iba 19

Jest不使用Webpack,因此它不知道如何加载除js/jsx之外的其他文件扩展名.要添加对其他扩展的支持,您需要编写自定义转换器.其中一个变换器是您在此片段中的配置中定义的Typescript变换器:

"transform": {
   "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
Run Code Online (Sandbox Code Playgroud)

现在您需要为svg文件添加转换器.让我们扩展你的jest配置

"transform": {
       "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js",
       "^.+\\.svg$": "<rootDir>/svgTransform.js" 
    },
Run Code Online (Sandbox Code Playgroud)

并使用以下内容在根目录中创建svgTransform.js文件

module.exports = {
  process() {
    return 'module.exports = {};';
  },
  getCacheKey() {
    // The output is always the same.
    return 'svgTransform';
  },
};
Run Code Online (Sandbox Code Playgroud)

当然,它是一个基本的变换器,总是返回相同的值.

链接到文档:http://facebook.github.io/jest/docs/en/configuration.html#transform-object-string-string


kal*_*m42 10

如果您使用了 @svgr/webpack 模块来允许 webpack 处理 svgs 的导入,@svgr 会提供一个页面来介绍如何使用 Jest 处理测试。资源在这里

为后人抄录。

/__mocks__/svgrMock.js

import * as React from 'react'
export default 'SvgrURL'
export const ReactComponent = 'div'
Run Code Online (Sandbox Code Playgroud)

package.json

"jest": {
  "moduleNameMapper": {
    "\\.svg": "<rootDir>/__mocks__/svgrMock.js"
  }
}
Run Code Online (Sandbox Code Playgroud)


tor*_*ord 5

您可以使用 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",

Run Code Online (Sandbox Code Playgroud)