【问题标题】:Angular 14 and Jest (cannot run tests)Angular 14 和 Jest(无法运行测试)
【发布时间】:2022-08-07 10:26:29
【问题描述】:

我正在将我的项目中的 Angular 版本升级到 14。但是当我尝试运行单元测试时,我得到了同样的错误:

  ● Test suite failed to run

    Cannot find module \'@angular/core/testing\' from \'node_modules/jest-preset-angular/build/config/setup-jest.js\'

    Require stack:
      node_modules/jest-preset-angular/build/config/setup-jest.js
      node_modules/jest-preset-angular/setup-jest.js
      setupJest.ts

这是当前的笑话配置:

jest.config.js

/** @type {import(\'@jest/types\').Config.InitialOptions} */
const config = {
  preset: \'jest-preset-angular\',
  setupFilesAfterEnv: [\'<rootDir>/setupJest.ts\'],
  testPathIgnorePatterns: [
    \'<rootDir>/node_modules/\',
    \'<rootDir>/dist/\'
  ],
  moduleNameMapper: {
    \"lodash-es\": \"lodash\",
  },
  globals: {
    \'ts-jest\': {
      tsconfig: \'<rootDir>/tsconfig.spec.json\',
      stringifyContentPathRegex: \'\\\\.html$\',
      diagnostics: {
        ignoreCodes: [151001]
      }
    }
  },
  restoreMocks: true,
  clearMocks: true
}

module.exports = config;

setupJest.ts

import \'jest-preset-angular/setup-jest\';
  • 你在运行什么版本?我正在使用 27.4.7 但也收到此错误

标签: angular jestjs


【解决方案1】:

所以我在网上搜索了很长一段时间,然后我遇到了这个解决方案,希望它也适用于你。

在 jest.config.js 文件中,如果您使用 moduleDirectories 配置,请将其从 moduleDirectories: ['node_modules', './'] 更改为 moduleDirectories: ['node_modules', __dirname]

【讨论】:

  • 对我不起作用我仍然得到同样的错误,你还有什么改变吗?
  • 更新到 jest 28 并预设到 v12 后,我得到了更多神秘的错误 xD
【解决方案2】:

当我遇到这种类型的错误时,我通常会在 package.json 中添加 Jest 配置所需的路径:

"modulePaths": [
 "<rootDir>",
 "/path/to/required"
],

但是,这种方法更适用于所需路径为src/app/ 等情况。

对于 node_modules,我通过在 package.json Jest 配置中添加 "transformIgnorePatterns": ["/node_modules/?!@angular"], 解决了这个问题。

另外,我建议您从根文件夹中点击npm install。以防万一 :)

【讨论】:

    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 2015-10-22
    • 2022-01-05
    • 2021-10-15
    • 2020-11-25
    • 2019-06-05
    • 2015-07-31
    • 1970-01-01
    相关资源
    最近更新 更多