我也需要相同的功能。我有大量想要运行的 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