angular - 如何在 2019 年 10 月使用 Jest 设置 Angular?
问题描述
作为一名 Angular 开发人员,我想摆脱 Karma/Jasmine并改用 Jest,这样我就可以快速而轻松地测试我的应用程序。不幸的是,我遇到了意想不到的问题。
在过去的几个小时里,我浏览了所有出现在 SERP 之上的教程:
- 使用 Jest 更快地测试 Angular - xfive.co(由 jestjs.io 推荐)
- 将 Jest 集成到 Angular 应用程序和库中 - angularindepth.com
- 如何在 Angular 中使用 Jest 又名让单元测试很棒(再次)-itnext.io
- 在 Angular 项目中使用 Jest 而不是 Karma 和 Jasmine - upcoding.fr
这是我所做的详细说明:
- 使用 .创建一个新的 Angular 应用程序
ng new my-application
。 - 更改目录:
cd my-application
. - 运行
npm start
(ng serve
) 和npm test
(ng test
) 以查看是否一切正常 - 它工作正常。 - 使用安装 Jest
npm install --save-dev jest jest-preset-angular @types/jest
- 将此添加到
package.json
:
{
...
"jest": {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": ["<rootDir>/src/setupJest.ts"]
}
}
- 将 npm 脚本更改
package.json
为以下内容:
"test": "jest",
"test:watch": "jest --watch",
- 在文件夹中
src
创建一个setupJest.ts
包含以下内容的文件:
import 'jest-preset-angular';
问题:
当我npm test
现在运行时,测试套件无法运行
File not found: <rootDir>/tsconfig.spec.json
我不知道我能做些什么,因为上面的所有教程似乎都没有处理这个问题。
请帮我!
先感谢您!
解决方案
你为什么不去试试brigbug 的Jest Schematic。我在过去几天(2019 年 11 月)刚刚完成了这项工作,并且运行良好。您只需在 VS Code 中运行以下命令,原理图就会处理所有事情:
ng add @briebug/jest-schematic
它删除了大部分茉莉花,但如果您运行此命令,它将卸载几乎所有与茉莉花相关的东西。在迁移到 jest-marbles 的过程中,我没有像我一样卸载 jasmine-marbles,但如果没有包含任何内容,只需将其附加到列表中即可。
我相信它也错过了从我的 tsconfig.spec.json 文件中的类型中删除茉莉花,所以我将其更新为以下内容:
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"module": "commonjs",
"types": ["jest", "node"],
"emitDecoratorMetadata": true,
"allowJs": true
},
"files": ["polyfills.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
我还必须更新 package.json 中新插入的 jest 部分的 globals 部分,并更改添加到 '/src/ **/src/**tsconfig.spec.json 中的 tsConfig 值,因为生成的没有指向我的 / src 目录。
"globals": {
"ts-jest": {
"tsConfig": "<rootDir>/src/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$",
"astTransformers": [
"jest-preset-angular/build/InlineFilesTransformer",
"jest-preset-angular/build/StripStylesTransformer"
]
}
推荐阅读
- python - 在 vs 代码中删除 python 的 Jedi linting
- javascript - 为什么当结果来自 API 时 addEventListener 不能与 id 属性一起使用
- ios - 点击表格视图单元格中的视频以在视图控制器中打开它
- python-3.x - 从文本文件发出请求时收到响应 404。Python
- java - 404 not found - 在此服务器上找不到请求的 URL /hello-servlet - 在 Google AppEngine 上部署后
- homebrew - 无法在 M1 Silicon 中安装 UPX
- html - 我可以在验证中使用 .val 作为我的 MAXLENGHT 吗?
- c# - 如何使用 windows 窗体 c# 中的按钮更改单选按钮组中的选中项?
- python - 关于 pygame.mask 函数的问题
- azure-cognitive-search - path_hierarchy_v2 不能与 Azure 认知搜索中的构面字段一起使用