Jest fails with “Unexpected token *” on import statement

前端 未结 5 597
南旧
南旧 2021-02-03 18:15

Why does Jest fail with \"Unexpected token *\" on a simple import statement...

Error log:

Admin@Admin-PC MINGW32 /d/project (master)
$ npm         


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-03 18:30

    I had a similar issue on a React + Typescript app.

    The first mistake I made was to define the jest.config.js as jest.config.ts

    Running on Node v12.latest

    Then the configuration that worked for me were the following:

    // jest.config.js
    
    module.exports = {
      preset: "ts-jest",
      testEnvironment: "node",
      roots: ["./src"],
      transform: { "\\.ts$": ["ts-jest"] },
      testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
      moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
      globals: {
        "ts-jest": {
          tsConfig: {
            // allow js in typescript
            allowJs: true,
          },
        },
      },
    };
    
    
    
    // tsconfig.json
    {
      "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react",
        "baseUrl": "."
      },
      "include": ["src"],
      "exclude": ["node_modules", "**/*.spec.ts"]
    }
    
    
    // package.json
    "devDependencies": {
        "@types/jest": "^26.0.5",
        "jest": "^26.1.0",
        "ts-jest": "^26.1.3"
    }
    
    

提交回复
热议问题