如何在 2019 年 10 月使用 Jest 设置 Angular?

Tem*_*gus 3 unit-testing typescript jestjs angular

作为一名 Angular 开发人员,我想摆脱 Karma/Jasmine改用 Jest,这样我就可以快速地测试我的应用程序,而没有任何痛苦。不幸的是,我遇到了意想不到的问题。

在过去的几个小时里,我浏览了所有出现在 SERP 之上的教程:

这是我所做的详细操作:

  1. 使用ng new my-application.
  2. 更改目录:cd my-application.
  3. 运行npm start( ng serve) 和npm test( ng test) 以查看是否一切正常 - 它有效。
  4. 安装 Jest 使用 npm install --save-dev jest jest-preset-angular @types/jest
  5. 将此添加到package.json
{
  ...
  "jest": {
    "preset": "jest-preset-angular",
    "setupFilesAfterEnv": ["<rootDir>/src/setupJest.ts"]
  }
}
Run Code Online (Sandbox Code Playgroud)
  1. 将 npm 脚本更改package.json为以下内容:
"test": "jest",
"test:watch": "jest --watch",
Run Code Online (Sandbox Code Playgroud)
  1. 在文件夹中src创建一个setupJest.ts包含以下内容的文件:
import 'jest-preset-angular';
Run Code Online (Sandbox Code Playgroud)

问题:
当我npm test现在运行时,测试套件无法运行

File not found: <rootDir>/tsconfig.spec.json
Run Code Online (Sandbox Code Playgroud)

我不知道我能做些什么,因为上面的所有教程似乎都没有处理这个问题。
请帮我!

先感谢您!

Cra*_*gly 7

你为什么不去试试brigbug 的Jest Schematic。我在过去几天(2019 年 11 月)刚刚完成了这项工作,而且效果很好。您只需在 VS Code 中运行以下命令,原理图就会处理一切:

ng add @briebug/jest-schematic
Run Code Online (Sandbox Code Playgroud)

它删除了大部分 jasmine,但如果您运行此命令,它将卸载几乎所有与 jasmine 相关的内容。我没有卸载 jasmine-marbles,因为我在迁移到 jest-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"]
}
Run Code Online (Sandbox Code Playgroud)

我还必须更新 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"
    ]
  }
Run Code Online (Sandbox Code Playgroud)