网站搜索

angular - 在移除 @types/jest 之后如何使用 jest.mock (^jest@24)


我最近将 @angular-builders/jest 从 7 更新到了 8。在迁移指南中,它说明我应该移除 @types/jest,因为它现在随 Jest v24 一起提供。(我也更新了我的 tsconfig)

到目前为止一切顺利。

但是现在我的测试失败了,原因是

error TS2304: Cannot find name 'jest'.

jest.mock('src/app/omitted');

error TS2304: Cannot find name 'jest'.

jest.clearAllMocks();

而 VS Code 将与 jest 全局变量无关。这在某种程度上是有道理的,因为我按照迁移指南的要求从 tsconfig 中移除了 typeRoots。

在 tsconfig.json(根目录,由 IDE 使用):

移除 typeRoots 数组

再次,由于 Jest 的类型定义包含在 jest 包中,而不位于 node_modules/@types 下,因此你不希望类型根被限制在特定的文件夹中。

但是怎么回事?迁移指南说我应该移除 @types/jest,但我怎样才能让它再次与 jest.mock 和 jest.clearAllMocks 配合使用呢?

我尝试过:

import { mock } from 'jest'; // mock isn't found
import * as jest from 'jest'; // jest.mock isn't found

请提供建议。

这是我的配置(与 simple-app 示例相同)

相关开发包

{
    "@angular-builders/jest": "^8.0.3",
    "jest": "^24.8.0",
    "jest-preset-angular": "^7.1.1",
    "ts-jest": "^24.0.2",
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "strict": true                // note strict mode
  }
}

tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "allowJs": true
  },
  "files": ["src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "my-project": {
      //...
      "architect": {
        //...
        "test": {
          "builder": "@angular-builders/jest:run",
          "options": {}
        }
      }
    }
  }
}

答案#1

显然仍然需要 @types/jest。迁移指南已进行调整以反映这一点。

现在配置看起来是这样的:

package.json

"@angular-builders/jest": "^8.0.3",
"@types/jest": "^24.0.15",
"jest": "^24.8.0",
"jest-preset-angular": "^7.1.1",
"ts-jest": "^24.0.2",

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "types": ["jest"],
    "strict": true                     // note strict mode, this isn't default
  }
}

tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec"
  },
  "files": ["src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}