【问题标题】:Jest: SVG require causes "SyntaxError: Unexpected token <"笑话测试失败:SyntaxError: Unexpected token <
【发布时间】:2018-03-29 05:04:09
【问题描述】:

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

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

【问题讨论】:

  • 尝试删除xml标签,只包含svg标签

标签: reactjs typescript jestjs


【解决方案1】:

如果你使用了 @svgr/webpack 模块来允许 webpack 处理导入 svgs,@svgr 提供了一个页面来介绍如何使用 Jest 处理测试。 Here

为后代复制。

/__mocks__/svgrMock.js

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

package.json

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

【讨论】:

    【解决方案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

    【讨论】:

    • 没问题!我删除了我的评论,因为你修复了它
    猜你喜欢
    • 1970-01-01
    • 2020-11-21
    • 2022-06-16
    • 2022-10-07
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多