Mocking the CSS webpack imports using identity-obj-proxy

I’m sure at some point you have encountered the SyntaxError: Unexpected token . error when preparing tests with Jest, it pointed at the dot of the CSS class name.

({“Object.“:function(module,exports,require,__dirname,__filename,global,jest){.my-class {
^
SyntaxError: Unexpected token .

If you are familiar with it then probably you have resolved it and probably already are using the identity-obj-proxy dependency in your project. For those who are searching for a solution please read on.

First install the identity-obj-proxy (dev) dependency in your project:

yarn add identity-obj-proxy --dev

After installation is complete you need to add the moduleNameMapper entry in the jest.config.json file:

    "moduleNameMapper": {
      "\\.(s?css|less)$": "identity-obj-proxy"
    },

Now you can run your tests without this error.

More about this can be found in the Jest docs.

This entry was posted in JavaScript, ReactJS and tagged , , , . Bookmark the permalink.