angular - 我可以通过 Angular CLI 运行 Jest 吗?

标签 angular unit-testing angular6 angular-cli jestjs

我已将 Angular 6 应用程序配置为在运行“npm run test”时使用 Jest 运行测试。这很好用。 我希望能够在执行“ng 测试”时运行那些相同的测试。是否可以配置 Angular CLI 来执行此操作?

最佳答案

我真的推荐使用 Jest builder如果你想在你的 Angular CLI 项目中切换到 Jest。我们刚刚在我们的一个项目中从 Karma 迁移到 Jest,它就像一个魅力。作为引用,以下是在新项目中切换到 Jest 的最少步骤:

  1. 创建项目

    $ ng new myapp
    $ cd myapp
    
  2. 删除 Karma 依赖项、配置文件和 test.ts:

    $ yarn remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
    $ rm src/karma.conf.js src/test.ts
    
  3. 安装 Jest 构建器,创建配置文件:

    $ yarn add --dev jest @angular-builders/jest
    $ touch src/jest.config.js
    
  4. src/tsconfig.spec.json 中切换到 commonjs:

    {
      "extends": "../tsconfig.json",
      "compilerOptions": {
        "outDir": "../out-tsc/spec",
        "module": "commonjs",
        "types": [
          "jasmine",
          "node"
        ]
      },
      "include": [
        "**/*.spec.ts",
        "**/*.d.ts"
      ]
    }
    
  5. 切换到 angular.json 中的 Jest 构建器:

    {
      ...
        "test": {
          "builder": "@angular-builders/jest:run",
          "options": {
            "styles": [
              "src/styles.css"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
      ...
    }
    

现在您将使用 Jest 运行测试:

$ ng test
 PASS  src/app/app.component.spec.ts
  AppComponent
    ✓ should create the app (223ms)
    ✓ should have as title 'myapp' (80ms)
    ✓ should render title in a h1 tag (70ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        3.704s
Ran all test suites.

关于angular - 我可以通过 Angular CLI 运行 Jest 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50786359/

相关文章:

angular - 此客户端应用程序未批准回调 URL。可以在您的应用程序设置中调整批准的回调 URL

angular - angular2 rc5 中的默认请求选项

unit-testing - 如何创建在另一个配方中定义的虚拟资源而不在测试运行中包含另一个配方?

angular - 我无法使用 Angular Material 的 mat-grid-tile 自定义样式属性

angularjs - Foundation 6/Bootstrap 4 - 在 webpack 中使用 sass 设置文件的正确方法

angular - 在 concat() 字符串中添加新行 - Angular 4

ios - 如何对静态属性进行单元测试?

android - 使用 Mockito 模拟 PreferenceManager

angular - (Angular 2/4/5/6) 订阅服务后从服务器获取错误响应

Angular react 形式 : valueChanges doesn't work as expected