删除@ types / jest之后如何使用jest.mock(^ jest @ 24)

时间:2019-06-19 09:02:08

标签: angular typescript jestjs angular-builder

我最近将@angular-builders/jest从7更新为8。在migration guide中,我指出应该删除@types/jest,因为Jest v24现在附带了它。 (我也是updated my tsconfig

到目前为止很好。

但是现在我的测试失败了

error TS2304: Cannot find name 'jest'.

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

error TS2304: Cannot find name 'jest'.

jest.clearAllMocks();

并且VS Code与玩笑的全局变量无关。根据迁移指南,我应该从tsconfig中删除typeRoots时哪种方法有意义。

  

在tsconfig.json(IDE使用的根目录)中:

     

删除typeRoots数组

     

再次,因为开玩笑的打字被打包在里面   开玩笑的包,并且不在您没有的node_modules / @ types下   希望类型根仅限于特定文件夹。

但有什么用呢?迁移指南说我应该删除@types/jest,但是如何使其与jest.mockjest.clearAllMocks再玩一次?

我尝试过:

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

请咨询。

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

相关开发包

{
    "@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 个答案:

答案 0 :(得分:0)

@types/jest显然是still neededmigration guide已进行调整以反映这一点。

现在的配置如下:

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"]
}