Jest gives an error: “SyntaxError: Unexpected token export”

前端 未结 4 1368
不知归路
不知归路 2020-12-17 08:45

I\'m using Jest to test my React app.

Recently, I added DeckGL to my app. My tests fail with this error:

Test suite failed to run

/my_project/node_         


        
相关标签:
4条回答
  • 2020-12-17 09:02

    Jest by default won't compile files in the node_modules directory.

    transformIgnorePatterns [array]

    Default: ["/node_modules/"]

    An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed.Default: ["/node_modules/"]

    DeckGL seems to be in ES6, to make jest able to read it, you need to compile this as well.
    To do that, just add an exception for DeckGL in the transformignorePatterns

    "transformIgnorePatterns": ["/node_modules/(?!deck\.gl)"]
    

    https://facebook.github.io/jest/docs/en/configuration.html#transformignorepatterns-array-string

    0 讨论(0)
  • 2020-12-17 09:06

    And if you are using 'create-react-app', it won't allow you to specify 'transformIgnorePatterns' via Jest property in package.json

    As per this https://github.com/facebook/create-react-app/issues/2537#issuecomment-390341713

    You can use CLI as below in your package.json to override and it works :

    "scripts": { "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!your-module-name)/\"", },

    0 讨论(0)
  • 2020-12-17 09:10

    This means, that a file is not transformed through TypeScript compiler, e.g. because it is a JS file with TS syntax, or it is published to npm as uncompiled source files. Here's what you can do.

    Adjust your transformIgnorePatterns whitelist:

    {
      "jest": {
        "transformIgnorePatterns": [
          "node_modules/(?!@ngrx|(?!deck.gl)|ng-dynamic)"
        ]
      }
    }

    By default Jest doesn't transform node_modules, because they should be valid JavaScript files. However, it happens that library authors assume that you'll compile their sources. So you have to tell this to Jest explicitly. Above snippet means that @ngrx, deck and ng-dynamic will be transforemed, even though they're node_modules.

    0 讨论(0)
  • 2020-12-17 09:16

    This is because Node.js cannot handle ES6 modules.

    You should transform your modules to CommonJS therefore.

    If you use Babel 7 =>

    Install npm install --save-dev @babel/plugin-transform-modules-commonjs

    And to use only for test cases add to .babelrc, Jest automatically gives NODE_ENV=test global variable.

    "env": {
        "test": {
          "plugins": ["@babel/plugin-transform-modules-commonjs"]
        }
    }
    

    or if you use Babel 6 =>

    npm install --save-dev babel-plugin-transform-es2015-modules-commonjs

    to .babelrc

    "env": {
        "test": {
          "plugins": ["transform-es2015-modules-commonjs"]
        }
    }
    
    0 讨论(0)
提交回复
热议问题