How to resolve “Cannot use import statement outside a module” in jest

前端 未结 7 1711
庸人自扰
庸人自扰 2020-12-15 16:39

I have a React application (not using Create React App) built using TypeScript, Jest, Webpack, and Babel. When trying to run \"yarn jest\", I get the following error:

相关标签:
7条回答
  • 2020-12-15 17:21

    I solved this by migrating the .babelrc file to babel.config.js! Shocker.

    0 讨论(0)
  • 2020-12-15 17:22

    Use Babel to transpile those JS Modules and you'll be able to write your tests with es6.

    Install Babel/preset-env

    npm i -D @babel/preset-env

    Create a babel configuration file with the preset

    //babel.config.js
    module.exports = {presets: ['@babel/preset-env']}
    
    0 讨论(0)
  • 2020-12-15 17:23

    Solution: my named imports were coming from index.js files and I believe ts-jest needed them as index.ts files (I'm using Typescript). If anyone else runs into this error, couldn't hurt to check if you derped your file extensions.

    I wasted a lot of time on this, unfortunately, but I learned a lot about webpack configurations and Babel.

    0 讨论(0)
  • 2020-12-15 17:25

    Also using Babel, Typescript and Jest. Had the same failure, driving me crazy for hours. Ended up creating a new babel.config.js file specifically for the tests. Had a large .babelrc that wasn't getting picked up by jest no matter what i did to it. Main app still uses the .babelrc as this overrides babel.config.js files.

    Install jest, ts-jest and babel-jest:

    npm i jest ts-jest babel-jest
    

    babel.config.js (only used by jest)

    module.exports = {presets: ['@babel/preset-env']}
    

    jest.config.js

    module.exports = {
      preset: 'ts-jest',
      transform: {
        '^.+\\.(ts|tsx)?$': 'ts-jest',
        "^.+\\.(js|jsx)$": "babel-jest",
      }
    };
    

    package.json

      "scripts": {
        "test": "jest"
    
    0 讨论(0)
  • 2020-12-15 17:25

    For future references,

    I solved the problem by using below jest config, after reading Logan Shoemaker's answer.

    module.exports = {
      verbose: true,
      setupFilesAfterEnv: ["<rootDir>src/setupTests.ts"],
      moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
      moduleDirectories: ["node_modules", "src"],
      moduleNameMapper: {
        "\\.(css|less|scss)$": "identity-obj-proxy"
      },
      transform: {
        '^.+\\.(ts|tsx)?$': 'ts-jest',
        "^.+\\.(js|jsx)$": "babel-jest",
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/file.js",
      }
    };
    
    0 讨论(0)
  • 2020-12-15 17:31

    try this thing if you are using babel 6

    1) Adding @babel/plugin-transform-modules-commonjs in the plugin section of babel.config.js

    or

    2) For my case import issue was due to the react file drop by adding that to transfromIgnorePatterns "transformIgnorePatterns": [ "/node_modules/(?!react-file-drop)" ],

    0 讨论(0)
提交回复
热议问题