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
请指教。
这是我的配置(与简单应用示例相同)
相关开发包
{
"@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"]
}
角.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": {}
}
}
}
}
}
解决方案
@types/jest
显然仍然需要。迁移指南已经过调整以反映这一点。
配置现在看起来像这样:
包.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"]
}
推荐阅读
- android - frida.TransportError:连接已关闭
- prolog - SWI-Prolog 如何重新加载工作区?
- sql-server - 不需要自托管的 SQL Server 报告解决方案
- javascript - 无法弄清楚如何制作像导航栏一样的搜索栏。搜索元素也不适用于 CSS
- flowtype - 带有比参数需要的额外属性的流错误传递对象
- python - 烧瓶读取和写入相同的csv
- python - 如何解决此代码片段中的 -(-(-(.... 部分?
- c# - 设置列表集合的属性
添加到列表时 - reactjs - 没有得到位置反应路由器?
- javascript - 文本编辑器是 RTL,但打印页面是 LRT