You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 14迁移后Jest测试报错:setup-jest.ts无法使用import语句

Angular 14迁移后Jest测试报错:Cannot use import statement outside a module

我已花费数小时寻找解决方案,但未找到适用且近期的相关内容。我正从Angular 13迁移至Angular 14,迁移完成后无法运行Jest测试,因此我回到《快速入门指南》,卸载并重新安装了最新版本的NPM包,我的setup-jest.ts文件无需修改,因此保持原样,但现在尝试运行测试时出现如下错误:

● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

...
    SyntaxError: Cannot use import statement outside a module

    > 1 | import 'jest-preset-angular/setup-jest';
        | ^
      2 | import './jestGlobalMocks';
      3 | import '@testing-library/jest-dom/extend-expect';
      4 |

以下是我package.json中的Jest配置:

"jest": {
  "preset": "jest-preset-angular",
  "roots": [
    "<rootDir>/src/"
  ],
  "setupFilesAfterEnv": ["<rootDir>/src/setup-jest.ts"],
  "moduleDirectories": ["node_modules", "<rootDir>"],
  "moduleFileExtensions": ["ts", "html", "js", "json", "mjs"],
  "transformIgnorePatterns": [
    "node_modules/(?!(jqwidgets-scripts)/)"
  ],
  "moduleNameMapper": {
    "^@services/(.*)$": "<rootDir>/src/app/services/$1",
    "^@components/(.*)$": "<rootDir>/src/app/components/$1",
    "^@shared/(.*)$": "<rootDir>/src/app/shared/$1",
    "^@app/(.*)$": "<rootDir>/src/app/$1",
    "^@base/(.*)$": "<rootDir>/src/$1"
  }
},

内容的提问来源于stack exchange,提问作者redOctober13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:07:46