首页 > 解决方案 > 如何在 2019 年 10 月使用 Jest 设置 Angular?

问题描述

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

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

这是我所做的详细说明:

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

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

File not found: <rootDir>/tsconfig.spec.json

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

先感谢您!

标签: angulartypescriptunit-testingjestjs

解决方案


你为什么不去试试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"
    ]
  }

推荐阅读