SyntaxError with Jest and React and importing CSS files

后端 未结 7 1156
-上瘾入骨i
-上瘾入骨i 2020-12-02 17:01

I am trying to get my first Jest Test to pass with React and Babel.

I am getting the following error:

SyntaxError: /Users/manueldupont/test/av

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 17:12

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

    {
       "jest":{
            "moduleNameMapper":{
                 "\\.(css|less|sass|scss)$": "/__mocks__/styleMock.js",
                 "\\.(gif|ttf|eot|svg)$": "/__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)$": "/__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

提交回复
热议问题