Importing images breaks jest test Importing images breaks jest test reactjs reactjs

Importing images breaks jest test


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!


For anyone looking into this problem. You have to do install npm install --save-dev identity-obj-proxy to get the necessary dependencies.

"jest": {    "moduleNameMapper": {      ".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"    }  }


If you want to use jest with webpack, you need to explicitly configure it as so. Take a look at this guide here: http://facebook.github.io/jest/docs/en/webpack.html