Image import breaks jest test

In React components importing assets (for example, importing a logo from "../../../assets/img/logo.png) gives this error

({"Object.": Function (module, export, required, __ directory_name, __ file name, global, joke) {PNG
    SyntaxError: invalid or unexpected token in ScriptTransformer._transformAndBuildScript (node_modules / jest-runtime / build / script_transformer.js : 305: 17)

my jest config

"jest": {
"testRegex": ".*\\.spec\\.js$",
"moduleFileExtensions": [
  "js",
  "jsx",
  "json"
],
"moduleDirectories": [
  "node_modules",
  "src",
  "assets"
],
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$/": "<rootDir>/__mocks__/fileMock.js",
  "\\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"verbose": true,
"bail": true
}

What am I missing?

+10
source share
2 answers

I'll make it as easy as possible

When you import image files, Jest tries to interpret binary image codes as .js, which leads to errors.

the only way out is to mock a default response anytime jest sees an image import

How do we do this?

  • Jest . , package.json
"jest": {
 "moduleNameMapper": {
      "\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\\.(css|less)$": "<rootDir>/mocks/fileMock.js"
    }
}

"Jest", "moduleNameMapper"

  • , fileMock.js fileMock.js .
module.exports = ''; 

Note > if you are using es6 u can use export default ''; to avoid an Eslint flag

, , .

. moduleNameMapper moduleNameMapper.

, . #cheers!

+6

Source: https://habr.com/ru/post/1688039/


All Articles