gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:23:53 28 4
gpt4 key购买 nike

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

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

  • Testing Angular Faster with Jest - xfive.co (jestjs.io 推荐)
  • Integrate Jest into an Angular application and library - angularindepth.com
  • How to use Jest in Angular aka make unit testing great (again) - itnext.io
  • Use Jest instead of Karma and Jasmine for your Angular project - upcoding.fr

  • 这是我所做的详细操作:
  • 使用 ng new my-application 创建一个新的 Angular 应用程序.
  • 更改目录:cd my-application .
  • 运行 npm start ( ng serve ) 和 npm test ( ng test ) 看看是否一切正常 - 它有效。
  • 使用 npm install --save-dev jest jest-preset-angular @types/jest 安装 Jest
  • 将此添加到 package.json :
  • {
    ...
    "jest": {
    "preset": "jest-preset-angular",
    "setupFilesAfterEnv": ["<rootDir>/src/setupJest.ts"]
    }
    }
  • 更改 package.json 中的 npm 脚本到以下:
  • "test": "jest",
    "test:watch": "jest --watch",
  • 进入文件夹src创建文件 setupJest.ts内容如下:
  • import 'jest-preset-angular';

    问题:
    当我跑 npm test现在,测试套件无法运行
    File not found: <rootDir>/tsconfig.spec.json

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

    先感谢您!

    最佳答案

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

    ng add @briebug/jest-schematic

    它删除了大部分 jasmine,但如果您运行此命令,它将卸载几乎所有与 jasmine 相关的内容。我没有卸载 jasmine-marbles,因为我在转向 jest-marbles 的过程中,但如果没有包含任何内容,只需将其附加到列表中。

    我相信它也没有从我的 tsconfig.spec.json 文件中的类型中删除 Jasmine ,所以我将其更新为以下内容:
    {
    "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"
    ]
    }

    关于angular - 如何在 2019 年 10 月使用 Jest 设置 Angular?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58555483/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com