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

前端 未结 7 1729
庸人自扰
庸人自扰 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: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"
    

提交回复
热议问题