|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import childProcess from 'child_process'; |
| 3 | +import os from 'os'; |
| 4 | + |
| 5 | +// This variable will act as a job queue that is consumed by a number of worker threads. Each item represents a test to run. |
| 6 | +const testPaths = childProcess.execSync('jest --listTests', { encoding: 'utf8' }).trim().split('\n'); |
| 7 | + |
| 8 | +const numTests = testPaths.length; |
| 9 | +const fails: string[] = []; |
| 10 | + |
| 11 | +// We're creating a worker for each CPU core. |
| 12 | +const workers = os.cpus().map(async (_, i) => { |
| 13 | + while (testPaths.length > 0) { |
| 14 | + const testPath = testPaths.pop(); |
| 15 | + console.log(`(Worker ${i}) Running test "${testPath}"`); |
| 16 | + await new Promise(resolve => { |
| 17 | + const jestProcess = childProcess.spawn('jest', ['--runTestsByPath', testPath as string, '--forceExit']); |
| 18 | + |
| 19 | + // We're collecting the output and logging it all at once instead of inheriting stdout and stderr, so that |
| 20 | + // test outputs of the individual workers aren't interwoven, in case they print at the same time. |
| 21 | + let output = ''; |
| 22 | + |
| 23 | + jestProcess.stdout.on('data', (data: Buffer) => { |
| 24 | + output = output + data.toString(); |
| 25 | + }); |
| 26 | + |
| 27 | + jestProcess.stderr.on('data', (data: Buffer) => { |
| 28 | + output = output + data.toString(); |
| 29 | + }); |
| 30 | + |
| 31 | + jestProcess.on('error', error => { |
| 32 | + console.log(output); |
| 33 | + console.log(`(Worker ${i}) Error in test "${testPath}"`, error); |
| 34 | + fails.push(`FAILED: "${testPath}"`); |
| 35 | + resolve(); |
| 36 | + }); |
| 37 | + |
| 38 | + jestProcess.on('exit', exitcode => { |
| 39 | + console.log(`(Worker ${i}) Finished test "${testPath}"`); |
| 40 | + console.log(output); |
| 41 | + if (exitcode !== 0) { |
| 42 | + fails.push(`FAILED: "${testPath}"`); |
| 43 | + } |
| 44 | + resolve(); |
| 45 | + }); |
| 46 | + }); |
| 47 | + } |
| 48 | +}); |
| 49 | + |
| 50 | +void Promise.all(workers).then(() => { |
| 51 | + console.log('-------------------'); |
| 52 | + console.log(`Successfully ran ${numTests} tests.`); |
| 53 | + if (fails.length > 0) { |
| 54 | + console.log('Not all tests succeeded:\n'); |
| 55 | + fails.forEach(fail => { |
| 56 | + console.log(`● ${fail}`); |
| 57 | + }); |
| 58 | + process.exit(1); |
| 59 | + } else { |
| 60 | + console.log('All tests succeeded.'); |
| 61 | + process.exit(0); |
| 62 | + } |
| 63 | +}); |
0 commit comments