Подтвердить что ты не робот

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

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

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

4b9b3361

Ответ 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"
  },
  ...
}

в

{
  ...
  "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: [
    ...
  ],
};

в

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

Ответ 2

Используйте серийный тестовый бегун:

npm install jest-serial-runner --save-dev

Настройте шутку, чтобы использовать его, например, в jest.config.js:

module.exports = {
   ...,
   runner: 'jest-serial-runner'
};

Вы можете использовать функцию проектов, чтобы предоставлять различные конфигурации для разных тестов.