Есть ли способ запустить некоторые тесты последовательно с Jest?

шутка запуск тестов параллельно по умолчанию, но есть флаг (--runInBand), что позволяет запускать весь набор последовательно (как указано здесь)

У меня есть некоторые тесты, которые не могут работать параллельно, но запуск всего набора последовательно занимает намного больше времени, поэтому мой вопрос в том, есть ли способ только запустить некоторые тесты таким образом (например, установка флага для этих тестов или что-то подобное).

1 ответов


мне тоже нужна была такая же функциональность. У меня есть большой набор наборов тестов интеграции Jest, которые я хочу запустить. Однако некоторые из них нельзя запускать параллельно из-за необходимости настройки и демонтажа общего ресурса. Итак, вот решение, которое я придумал.

я package.json скрипты от:

{
  ...
  "scripts": {
    ...
    "test": "npm run test:unit && npm run test:integration",
    "test:integration": "jest --config=__tests__/integration/jest.config.js",
    "test:unit": "jest --config=__tests__/unit/jest.config.js"
  },
  ...
}

to

{
  ...
  "scripts": {
    ...
    "test": "npm run test:unit && npm run test:integration",
    "test:integration": "npm run test:integration:sequential && npm run test:integration:parallel",
    "test:integration:parallel": "jest --config=__tests__/integration/jest.config.js",
    "test:integration:sequential": "jest --config=__tests__/integration/jest.config.js --runInBand",
    "test:unit": "jest --config=__tests__/unit/jest.config.js"
  },
  ...
}
я __tests__/integration/jest.config.js С
module.exports = {
  // Note: rootDir is relative to the directory containing this file.
  rootDir: './src',
  setupFiles: [
    '../setup.js',
  ],
  testPathIgnorePatterns: [
    ...
  ],
};

to

const Path = require('path');

const { defaults } = require('jest-config');
const klawSync = require('klaw-sync')
const mm = require('micromatch');

// Note: rootDir is relative to the directory containing this file.
const rootDir = './src';
const { testMatch } = defaults;

// TODO: Add the paths to the test suites that need to be run
// sequentially to this array.
const sequentialTestPathMatchPatterns = [
  '<rootDir>/TestSuite1ToRunSequentially.spec.js',
  '<rootDir>/TestSuite2ToRunSequentially.spec.js',
  ...
];

const parallelTestPathIgnorePatterns = [
  ...
];

let testPathIgnorePatterns = [
  ...parallelTestPathIgnorePatterns,
  ...sequentialTestPathMatchPatterns,
];

const sequential = process.argv.includes('--runInBand');
if (sequential) {
  const absRootDir = Path.resolve(__dirname, rootDir);
  let filenames = klawSync(absRootDir, { nodir: true })
    .map(file => file.path)
    .map(file => file.replace(absRootDir, ''))
    .map(file => file.replace(/\/g, '/'))
    .map(file => '<rootDir>' + file);
  filenames = mm(filenames, testMatch);
  testPathIgnorePatterns = mm.not(filenames, sequentialTestPathMatchPatterns);
}

module.exports = {
  rootDir,
  setupFiles: [
    '../setup.js',
  ],
  testMatch,
  testPathIgnorePatterns,
};

обновление jest.config.js зависит от jest-config, klaw-sync и micromatch.

npm install --save-dev jest-config klaw-sync micromatch

теперь, вы можете запустить npm run test:integration:sequential если вы только хотите запустить тесты, которые необходимо выполнить последовательно.

или выполните команду npm run test:integration:parallel для параллельных испытаний.

или выполните команду npm run test:integration для первого запуска последовательных тестов. Затем, когда это будет завершено, будут запущены параллельные тесты.

или выполните команду npm run test для запуска как модульных, так и интеграционных тестов.

Примечание: структура каталогов, которую я использую с моим модульные и интеграционные тесты:

__tests__
  integration
    src
      *.spec.js
      *.test.js
    jest.config.js
  unit
    src
      *.spec.js
      *.test.js
    jest.config.js