SyntaxError: Invalid or unexpected token @import

怎甘沉沦 提交于 2021-02-09 02:45:51

问题


I am trying to add Jest and Enzyme to a React webpack project.

Everything is working, until I add tests to a component, with a style sheet importing google fonts.

The error I get is:

● Test suite failed to run
    /Users/dev/Code/Git/react-redux-webpack/src/App.sass:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){@import url('https://fonts.googleapis.com/css?family=Barlow+Condensed')
                                                                                             ^
    SyntaxError: Invalid or unexpected token

The sass file looks like:

@import url('https://fonts.googleapis.com/css?family=Barlow+Condensed')

body
    background: #f9f9f9
    color: #444444
    font-family: 'Barlow Condensed', sans-serif
    text-align: center

.container
    width: 100%
    max-width: 960px
    margin: 0 auto

.container__logo--image
    position: absolute
    top: 50%
    left: 50%
    margin-left: -75px
    margin-top: -75px

My .babelrc:

{
  "presets": [
    "react",
    "stage-0",
    [
      "env",
      {
        "targets": {
          "node": "6.10",
          "browsers": ["last 2 versions", "safari >= 7"]
        }
      }
    ]
  ],
  "plugins": ["transform-class-properties"]
}

I have all the required loaders in webpack, I can build and serve the sass all day with no issues. It is the introduction of Jest I am struggling with.

I have pushed a branch with the current state of code here https://github.com/nombienombie/react-redux-webpack/tree/feature/jest-unit-tests


回答1:


I added the following to my package.json:

  "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|sass)$": "<rootDir>/__mocks__/styleMock.js"
    }
  },

and added the following in a mocks folder:

fileMock.js

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

styleMock.js

module.exports = {}



回答2:


Since they are not compiled by Webpack, static assets imported by tests should be handled somehow.

The typical approach consists of mocking them out since not relevant for testing purpose. Jest expose a moduleNameMapper option to easily mock/proxy them.




回答3:


One more thing to add on the answer given by @Harry,

if you are using jest.config.js file then add on it instead of package.json

  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
      '<rootDir>/src/__mock__/fileMock.js',
    '\\.(css|less)$': '<rootDir>/src/__mock__/styleMock.js',
  },



来源:https://stackoverflow.com/questions/47541393/syntaxerror-invalid-or-unexpected-token-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!