'Jest: SVG require causes "SyntaxError: Unexpected token <"

Not sure where to look for this error.

Using Typescript with React, and Jest and Enzyme for unit testing.

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"
    ]
  }

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 <

Edit: 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?



Solution 1:[1]

If you have used the @svgr/webpack module to allow webpack to handle importing svgs @svgr provides a page that goes over how to handle testing with Jest. Here

Copied for posterity.

/__mocks__/svgrMock.js

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

In package.json

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kalm42