首页 > 解决方案 > 业力并行执行测试用例两次

问题描述

我正在将我的 Angular 从 4 升级到版本 7。我有 karma-parallel 来运行 tdd,它在 Angular 4 上按预期工作。现在升级到 7 后,相同的测试在停止执行之前运行了两次。我的 karma.conf.js 如下,

const path = require('path');
module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: [ 'parallel', 'jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-parallel'),
      require('karma-jasmine'),
      require('karma-spec-reporter'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    parallelOptions: {
      executors: 3, // For Jenkins enterprise, stick to 6 executors. For local laptop, change to 3-5
      shardStrategy: 'round-robin'
    },
    client: {
      jasmine: {
        random: false
      },
      clearContext: false
    },
    coverageIstanbulReporter: {
      reports: ['html', 'json', 'text-summary'],
      dir: path.join(__dirname, 'coverage'),
      fixWebpackSourcePaths: true
    },    
    reporters: ['spec', 'kjhtml'],
    specReporter: {
         maxLogLines: 5,
         suppressErrorSummary: true,
         suppressFailed: false,
         suppressPassed: false,
         suppressSkipped: true,
         showSpecTiming: true,
         failFast: false
      },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadlessNoSandbox'],
    customLaunchers: {
        ChromeHeadlessNoSandbox: {
            base: 'ChromeHeadless',
            flags: [
                '--no-sandbox', // required to run without privileges in docker
                '--user-data-dir=/tmp/chrome-test-profile',
                '--disable-web-security',
                '--no-proxy=http://0.0.0.0:9876/'
            ]
        }
    },
    singleRun: true,
    concurrency: Infinity,
    captureTimeout: 180000,
    browserDisconnectTimeout: 90000,
    browserNoActivityTimeout: 180000
  });
};

用于运行测试用例的命令如下,

node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng test --watch=false --code-coverage --source-map=false

请指教。

标签: angulartddkarma-jasmine

解决方案


当您运行ng test时,它将运行所有项目的测试。

例如,如果您的 中有这两个项目angular.json

  • hello-world(有 10 个测试)
  • utilities(有 100 次测试)

那么当你运行ng test它时,它会同时运行hello-world和的测试utilities

但是,如果您使用带有监视文件或启用自动监视的 Karma,它将在第一个项目处停止,因此您只会看到 10 个测试运行(或 100 个测试,具体取决于项目的顺序)。然后当你 Ctrl+C 退出 Karma 进程时,它将继续下一个项目,编译它并运行测试。因此,您将进行两次测试。

该怎么办?

  • 如果您有多个 Angular 应用程序但正在将一个部署到生产环境中,您应该使用ng test <app>您正在部署的项目名称。
  • 如果您有 Angular 应用程序和,您将需要测试应用程序和库:ng test <app> && ng test <library>
  • 如果您想运行完整的测试套件,只需执行ng test并且不要忘记将 Karma 更改为运行单个测试运行,而不是自动监视更改的文件!
  • 更新karma.conf.js每个项目的设置以确保它具有正确的设置(不观看、单次运行、使用正确的浏览器)

推荐阅读