UNPKG

11.3 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', {
4 value: true
5});
6exports.default = runJest;
7function path() {
8 const data = _interopRequireWildcard(require('path'));
9 path = function () {
10 return data;
11 };
12 return data;
13}
14function _perf_hooks() {
15 const data = require('perf_hooks');
16 _perf_hooks = function () {
17 return data;
18 };
19 return data;
20}
21function _chalk() {
22 const data = _interopRequireDefault(require('chalk'));
23 _chalk = function () {
24 return data;
25 };
26 return data;
27}
28function _exit() {
29 const data = _interopRequireDefault(require('exit'));
30 _exit = function () {
31 return data;
32 };
33 return data;
34}
35function fs() {
36 const data = _interopRequireWildcard(require('graceful-fs'));
37 fs = function () {
38 return data;
39 };
40 return data;
41}
42function _console() {
43 const data = require('@jest/console');
44 _console = function () {
45 return data;
46 };
47 return data;
48}
49function _testResult() {
50 const data = require('@jest/test-result');
51 _testResult = function () {
52 return data;
53 };
54 return data;
55}
56function _jestResolve() {
57 const data = _interopRequireDefault(require('jest-resolve'));
58 _jestResolve = function () {
59 return data;
60 };
61 return data;
62}
63function _jestUtil() {
64 const data = require('jest-util');
65 _jestUtil = function () {
66 return data;
67 };
68 return data;
69}
70function _jestWatcher() {
71 const data = require('jest-watcher');
72 _jestWatcher = function () {
73 return data;
74 };
75 return data;
76}
77var _SearchSource = _interopRequireDefault(require('./SearchSource'));
78var _TestScheduler = require('./TestScheduler');
79var _collectHandles = _interopRequireDefault(require('./collectHandles'));
80var _getNoTestsFoundMessage = _interopRequireDefault(
81 require('./getNoTestsFoundMessage')
82);
83var _runGlobalHook = _interopRequireDefault(require('./runGlobalHook'));
84function _interopRequireDefault(obj) {
85 return obj && obj.__esModule ? obj : {default: obj};
86}
87function _getRequireWildcardCache(nodeInterop) {
88 if (typeof WeakMap !== 'function') return null;
89 var cacheBabelInterop = new WeakMap();
90 var cacheNodeInterop = new WeakMap();
91 return (_getRequireWildcardCache = function (nodeInterop) {
92 return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
93 })(nodeInterop);
94}
95function _interopRequireWildcard(obj, nodeInterop) {
96 if (!nodeInterop && obj && obj.__esModule) {
97 return obj;
98 }
99 if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
100 return {default: obj};
101 }
102 var cache = _getRequireWildcardCache(nodeInterop);
103 if (cache && cache.has(obj)) {
104 return cache.get(obj);
105 }
106 var newObj = {};
107 var hasPropertyDescriptor =
108 Object.defineProperty && Object.getOwnPropertyDescriptor;
109 for (var key in obj) {
110 if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
111 var desc = hasPropertyDescriptor
112 ? Object.getOwnPropertyDescriptor(obj, key)
113 : null;
114 if (desc && (desc.get || desc.set)) {
115 Object.defineProperty(newObj, key, desc);
116 } else {
117 newObj[key] = obj[key];
118 }
119 }
120 }
121 newObj.default = obj;
122 if (cache) {
123 cache.set(obj, newObj);
124 }
125 return newObj;
126}
127/**
128 * Copyright (c) Meta Platforms, Inc. and affiliates.
129 *
130 * This source code is licensed under the MIT license found in the
131 * LICENSE file in the root directory of this source tree.
132 */
133
134const getTestPaths = async (
135 globalConfig,
136 source,
137 outputStream,
138 changedFiles,
139 jestHooks,
140 filter
141) => {
142 const data = await source.getTestPaths(globalConfig, changedFiles, filter);
143 if (!data.tests.length && globalConfig.onlyChanged && data.noSCM) {
144 new (_console().CustomConsole)(outputStream, outputStream).log(
145 'Jest can only find uncommitted changed files in a git or hg ' +
146 'repository. If you make your project a git or hg ' +
147 'repository (`git init` or `hg init`), Jest will be able ' +
148 'to only run tests related to files changed since the last ' +
149 'commit.'
150 );
151 }
152 const shouldTestArray = await Promise.all(
153 data.tests.map(test =>
154 jestHooks.shouldRunTestSuite({
155 config: test.context.config,
156 duration: test.duration,
157 testPath: test.path
158 })
159 )
160 );
161 const filteredTests = data.tests.filter((_test, i) => shouldTestArray[i]);
162 return {
163 ...data,
164 allTests: filteredTests.length,
165 tests: filteredTests
166 };
167};
168const processResults = async (runResults, options) => {
169 const {
170 outputFile,
171 json: isJSON,
172 onComplete,
173 outputStream,
174 testResultsProcessor,
175 collectHandles
176 } = options;
177 if (collectHandles) {
178 runResults.openHandles = await collectHandles();
179 } else {
180 runResults.openHandles = [];
181 }
182 if (testResultsProcessor) {
183 const processor = await (0, _jestUtil().requireOrImportModule)(
184 testResultsProcessor
185 );
186 runResults = await processor(runResults);
187 }
188 if (isJSON) {
189 if (outputFile) {
190 const cwd = (0, _jestUtil().tryRealpath)(process.cwd());
191 const filePath = path().resolve(cwd, outputFile);
192 fs().writeFileSync(
193 filePath,
194 `${JSON.stringify((0, _testResult().formatTestResults)(runResults))}\n`
195 );
196 outputStream.write(
197 `Test results written to: ${path().relative(cwd, filePath)}\n`
198 );
199 } else {
200 process.stdout.write(
201 `${JSON.stringify((0, _testResult().formatTestResults)(runResults))}\n`
202 );
203 }
204 }
205 onComplete?.(runResults);
206};
207const testSchedulerContext = {
208 firstRun: true,
209 previousSuccess: true
210};
211async function runJest({
212 contexts,
213 globalConfig,
214 outputStream,
215 testWatcher,
216 jestHooks = new (_jestWatcher().JestHook)().getEmitter(),
217 startRun,
218 changedFilesPromise,
219 onComplete,
220 failedTestsCache,
221 filter
222}) {
223 // Clear cache for required modules - there might be different resolutions
224 // from Jest's config loading to running the tests
225 _jestResolve().default.clearDefaultResolverCache();
226 const Sequencer = await (0, _jestUtil().requireOrImportModule)(
227 globalConfig.testSequencer
228 );
229 const sequencer = new Sequencer();
230 let allTests = [];
231 if (changedFilesPromise && globalConfig.watch) {
232 const {repos} = await changedFilesPromise;
233 const noSCM = Object.keys(repos).every(scm => repos[scm].size === 0);
234 if (noSCM) {
235 process.stderr.write(
236 `\n${_chalk().default.bold(
237 '--watch'
238 )} is not supported without git/hg, please use --watchAll\n`
239 );
240 (0, _exit().default)(1);
241 }
242 }
243 const searchSources = contexts.map(
244 context => new _SearchSource.default(context)
245 );
246 _perf_hooks().performance.mark('jest/getTestPaths:start');
247 const testRunData = await Promise.all(
248 contexts.map(async (context, index) => {
249 const searchSource = searchSources[index];
250 const matches = await getTestPaths(
251 globalConfig,
252 searchSource,
253 outputStream,
254 changedFilesPromise && (await changedFilesPromise),
255 jestHooks,
256 filter
257 );
258 allTests = allTests.concat(matches.tests);
259 return {
260 context,
261 matches
262 };
263 })
264 );
265 _perf_hooks().performance.mark('jest/getTestPaths:end');
266 if (globalConfig.shard) {
267 if (typeof sequencer.shard !== 'function') {
268 throw new Error(
269 `Shard ${globalConfig.shard.shardIndex}/${globalConfig.shard.shardCount} requested, but test sequencer ${Sequencer.name} in ${globalConfig.testSequencer} has no shard method.`
270 );
271 }
272 allTests = await sequencer.shard(allTests, globalConfig.shard);
273 }
274 allTests = await sequencer.sort(allTests);
275 if (globalConfig.listTests) {
276 const testsPaths = Array.from(new Set(allTests.map(test => test.path)));
277 /* eslint-disable no-console */
278 if (globalConfig.json) {
279 console.log(JSON.stringify(testsPaths));
280 } else {
281 console.log(testsPaths.join('\n'));
282 }
283 /* eslint-enable */
284
285 onComplete &&
286 onComplete((0, _testResult().makeEmptyAggregatedTestResult)());
287 return;
288 }
289 if (globalConfig.onlyFailures) {
290 if (failedTestsCache) {
291 allTests = failedTestsCache.filterTests(allTests);
292 } else {
293 allTests = await sequencer.allFailedTests(allTests);
294 }
295 }
296 const hasTests = allTests.length > 0;
297 if (!hasTests) {
298 const {exitWith0, message: noTestsFoundMessage} = (0,
299 _getNoTestsFoundMessage.default)(testRunData, globalConfig);
300 if (exitWith0) {
301 new (_console().CustomConsole)(outputStream, outputStream).log(
302 noTestsFoundMessage
303 );
304 } else {
305 new (_console().CustomConsole)(outputStream, outputStream).error(
306 noTestsFoundMessage
307 );
308 (0, _exit().default)(1);
309 }
310 } else if (
311 allTests.length === 1 &&
312 globalConfig.silent !== true &&
313 globalConfig.verbose !== false
314 ) {
315 const newConfig = {
316 ...globalConfig,
317 verbose: true
318 };
319 globalConfig = Object.freeze(newConfig);
320 }
321 let collectHandles;
322 if (globalConfig.detectOpenHandles) {
323 collectHandles = (0, _collectHandles.default)();
324 }
325 if (hasTests) {
326 _perf_hooks().performance.mark('jest/globalSetup:start');
327 await (0, _runGlobalHook.default)({
328 allTests,
329 globalConfig,
330 moduleName: 'globalSetup'
331 });
332 _perf_hooks().performance.mark('jest/globalSetup:end');
333 }
334 if (changedFilesPromise) {
335 const changedFilesInfo = await changedFilesPromise;
336 if (changedFilesInfo.changedFiles) {
337 testSchedulerContext.changedFiles = changedFilesInfo.changedFiles;
338 const sourcesRelatedToTestsInChangedFilesArray = (
339 await Promise.all(
340 contexts.map(async (_, index) => {
341 const searchSource = searchSources[index];
342 return searchSource.findRelatedSourcesFromTestsInChangedFiles(
343 changedFilesInfo
344 );
345 })
346 )
347 ).reduce((total, paths) => total.concat(paths), []);
348 testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set(
349 sourcesRelatedToTestsInChangedFilesArray
350 );
351 }
352 }
353 const scheduler = await (0, _TestScheduler.createTestScheduler)(
354 globalConfig,
355 {
356 startRun,
357 ...testSchedulerContext
358 }
359 );
360
361 // @ts-expect-error - second arg is unsupported (but harmless) in Node 14
362 _perf_hooks().performance.mark('jest/scheduleAndRun:start', {
363 detail: {
364 numTests: allTests.length
365 }
366 });
367 const results = await scheduler.scheduleTests(allTests, testWatcher);
368 _perf_hooks().performance.mark('jest/scheduleAndRun:end');
369 _perf_hooks().performance.mark('jest/cacheResults:start');
370 sequencer.cacheResults(allTests, results);
371 _perf_hooks().performance.mark('jest/cacheResults:end');
372 if (hasTests) {
373 _perf_hooks().performance.mark('jest/globalTeardown:start');
374 await (0, _runGlobalHook.default)({
375 allTests,
376 globalConfig,
377 moduleName: 'globalTeardown'
378 });
379 _perf_hooks().performance.mark('jest/globalTeardown:end');
380 }
381 _perf_hooks().performance.mark('jest/processResults:start');
382 await processResults(results, {
383 collectHandles,
384 json: globalConfig.json,
385 onComplete,
386 outputFile: globalConfig.outputFile,
387 outputStream,
388 testResultsProcessor: globalConfig.testResultsProcessor
389 });
390 _perf_hooks().performance.mark('jest/processResults:end');
391}