Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

reactjs - Importing images breaks jest test

In React components importing assets (ex, import logo from "../../../assets/img/logo.png) gives such error

({"Object.":function(module,exports,require,__dirname,__filename,global,jest){?PNG
SyntaxError: Invalid or unexpected token at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)

my jest config is

"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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you import image files, Jest tries to interpret the binary codes of the images as .js, hence runs into errors.

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

How do we do this?

  • first you tell Jest to run the mock file each time an image import is encountered. you do this by adding the key below to your package.json file
"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"
    }
}

Note: if you already have the "Jest" key, just add the "moduleNameMapper" child in it

  • lastly, create a mocks folder in your root and create fileMock.js file inside it. populate the file with the snippet below
module.exports = ''; 

Note: If you are using es6 you can use export default ''; to avoid an Eslint flag

when you are done with the above steps, you can restart the test and you are good to go.

Note. remember to add the varying extensions of your image files in the moduleNameMapper so that they can be mocked.

I hope I have been able to help. #cheers!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...