SyntaxError with Jest and React and importing CSS files SyntaxError with Jest and React and importing CSS files reactjs reactjs

SyntaxError with Jest and React and importing CSS files


moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.

Create a file like this in your project (you can use a different name or path if you’d like):

config/CSSStub.js

module.exports = {};

This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:

'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'

Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.

Read more in this guide.


I solved this by using the moduleNameMapper key in the jest configurations in the package.json file

{   "jest":{        "moduleNameMapper":{             "\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",             "\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"        }   }}

After this you will need to create the two files as described below

  • __mocks__/styleMock.js

    module.exports = {};

  • __mocks__/fileMock.js

    module.exports = 'test-file-stub';

If you are using CSS Modules then it's better to mock a proxy to enable className lookups.hence your configurations will change to:

{  "jest":{     "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|sass)$": "identity-obj-proxy"    },  }}

But you will need to install identity-obj-proxy package as a dev dependancy i.e.

yarn add identity-obj-proxy -D

For more information. You can refer to the jest docs


UPDATE who use create-react-app from feb 2018. You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.So my jest.config.js look like this:

module.exports = {...,  "moduleNameMapper": {    "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",    "\\.(scss|sass|css)$": "identity-obj-proxy"  }}

and it skips scss files and @import quite well.

Backing my answer i followed jest webpack