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

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

    For future references,

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

    module.exports = {
      verbose: true,
      setupFilesAfterEnv: ["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)$": "/__mocks__/file.js",
      }
    };
    

提交回复
热议问题