Skip to content

Commit

Permalink
Use prettier 4/n. (jestjs#3128)
Browse files Browse the repository at this point in the history
* Use prettier 4/n.

* Fix Flow.

* Fix lint errors.

* More prettier/eslint fixes.

* Pretty print jsonlint, because why the hell not.
  • Loading branch information
cpojer authored and skovhus committed Apr 29, 2017
1 parent dd0ca66 commit fda0a7b
Show file tree
Hide file tree
Showing 64 changed files with 3,687 additions and 3,073 deletions.
30 changes: 16 additions & 14 deletions packages/babel-jest/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,22 @@ const createTransformer = (options: any) => {
configString: string,
{instrument, watch}: TransformOptions,
): string {
return crypto
.createHash('md5')
.update(THIS_FILE)
.update('\0', 'utf8')
.update(fileData)
.update('\0', 'utf8')
.update(configString)
.update('\0', 'utf8')
// Don't use the in-memory cache in watch mode because the .babelrc
// file may be modified.
.update(getBabelRC(filename, {useCache: !watch}))
.update('\0', 'utf8')
.update(instrument ? 'instrument' : '')
.digest('hex');
return (
crypto
.createHash('md5')
.update(THIS_FILE)
.update('\0', 'utf8')
.update(fileData)
.update('\0', 'utf8')
.update(configString)
.update('\0', 'utf8')
// Don't use the in-memory cache in watch mode because the .babelrc
// file may be modified.
.update(getBabelRC(filename, {useCache: !watch}))
.update('\0', 'utf8')
.update(instrument ? 'instrument' : '')
.digest('hex')
);
},
process(
src: string,
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-config-fb-strict/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module.exports = Object.assign({}, fbjsConfig, {
'computed-property-spacing': [2, 'never'],
'eol-last': [2],
'flowtype/object-type-delimiter': [2, 'comma'],
'indent': [0],
'jest/no-focused-tests': [2],
'jest/no-identical-title': [2],
'jest/valid-expect': [2],
Expand Down
144 changes: 67 additions & 77 deletions packages/jest-cli/src/SearchSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,11 @@ export type PatternInfo = {|
const git = changedFiles.git;
const hg = changedFiles.hg;

const determineSCM = path => Promise.all([
git.isGitRepository(path),
hg.isHGRepository(path),
]);
const determineSCM = path =>
Promise.all([git.isGitRepository(path), hg.isHGRepository(path)]);
const pathToRegex = p => replacePathSepForRegex(p);
const pluralize = (
word: string,
count: number,
ending: string,
) => `${count} ${word}${count === 1 ? '' : ending}`;
const pluralize = (word: string, count: number, ending: string) =>
`${count} ${word}${count === 1 ? '' : ending}`;

const globsToMatcher = (globs: ?Array<Glob>) => {
if (globs == null || globs.length === 0) {
Expand Down Expand Up @@ -114,22 +109,20 @@ class SearchSource {
skipNodeResolution: false,
};

this._rootPattern =
new RegExp(config.roots.map(
dir => escapePathForRegex(dir),
).join('|'));
this._rootPattern = new RegExp(
config.roots.map(dir => escapePathForRegex(dir)).join('|'),
);

const ignorePattern = config.testPathIgnorePatterns;
this._testIgnorePattern =
ignorePattern.length ? new RegExp(ignorePattern.join('|')) : null;
this._testIgnorePattern = ignorePattern.length
? new RegExp(ignorePattern.join('|'))
: null;

this._testPathCases = {
roots: path => this._rootPattern.test(path),
testMatch: globsToMatcher(config.testMatch),
testPathIgnorePatterns: path => (
!this._testIgnorePattern ||
!this._testIgnorePattern.test(path)
),
testPathIgnorePatterns: path =>
!this._testIgnorePattern || !this._testIgnorePattern.test(path),
testRegex: regexToMatcher(config.testRegex),
};
}
Expand All @@ -153,37 +146,35 @@ class SearchSource {
const testCasesKeys = Object.keys(testCases);

data.paths = allPaths.filter(path => {
return testCasesKeys.reduce((flag, key) => {
if (testCases[key](path)) {
data.stats[key] = ++data.stats[key] || 1;
return flag && true;
}
data.stats[key] = data.stats[key] || 0;
return false;
}, true);
return testCasesKeys.reduce(
(flag, key) => {
if (testCases[key](path)) {
data.stats[key] = ++data.stats[key] || 1;
return flag && true;
}
data.stats[key] = data.stats[key] || 0;
return false;
},
true,
);
});

return data;
}

_getAllTestPaths(
testPathPattern: StrOrRegExpPattern,
): SearchResult {
_getAllTestPaths(testPathPattern: StrOrRegExpPattern): SearchResult {
return this._filterTestPathsWithStats(
this._hasteContext.hasteFS.getAllFiles(),
testPathPattern,
);
}

isTestFilePath(path: Path): boolean {
return Object.keys(this._testPathCases).every(key => (
this._testPathCases[key](path)
));
return Object.keys(this._testPathCases).every(key =>
this._testPathCases[key](path));
}

findMatchingTests(
testPathPattern: StrOrRegExpPattern,
): SearchResult {
findMatchingTests(testPathPattern: StrOrRegExpPattern): SearchResult {
return this._getAllTestPaths(testPathPattern);
}

Expand All @@ -203,9 +194,7 @@ class SearchSource {
};
}

findRelatedTestsFromPattern(
paths: Array<Path>,
): SearchResult {
findRelatedTestsFromPattern(paths: Array<Path>): SearchResult {
if (Array.isArray(paths) && paths.length) {
const resolvedPaths = paths.map(p => path.resolve(process.cwd(), p));
return this.findRelatedTests(new Set(resolvedPaths));
Expand All @@ -214,22 +203,24 @@ class SearchSource {
}

findChangedTests(options: Options): Promise<SearchResult> {
return Promise.all(this._config.roots.map(determineSCM))
.then(repos => {
if (!repos.every(([gitRepo, hgRepo]) => gitRepo || hgRepo)) {
return {
noSCM: true,
paths: [],
};
}
return Promise.all(Array.from(repos).map(([gitRepo, hgRepo]) => {
return Promise.all(this._config.roots.map(determineSCM)).then(repos => {
if (!repos.every(([gitRepo, hgRepo]) => gitRepo || hgRepo)) {
return {
noSCM: true,
paths: [],
};
}
return Promise.all(
Array.from(repos).map(([gitRepo, hgRepo]) => {
return gitRepo
? git.findChangedFiles(gitRepo, options)
: hg.findChangedFiles(hgRepo, options);
})).then(changedPathSets => this.findRelatedTests(
}),
).then(changedPathSets =>
this.findRelatedTests(
new Set(Array.prototype.concat.apply([], changedPathSets)),
));
});
});
}

getNoTestsFoundMessage(
Expand All @@ -238,40 +229,40 @@ class SearchSource {
data: SearchResult,
): string {
if (patternInfo.onlyChanged) {
return (
chalk.bold(
'No tests found related to files changed since last commit.\n',
) +
return chalk.bold(
'No tests found related to files changed since last commit.\n',
) +
chalk.dim(
patternInfo.watch ?
'Press `a` to run all tests, or run Jest with `--watchAll`.' :
'Run Jest without `-o` to run all tests.',
)
);
patternInfo.watch
? 'Press `a` to run all tests, or run Jest with `--watchAll`.'
: 'Run Jest without `-o` to run all tests.',
);
}

const testPathPattern = SearchSource.getTestPathPattern(patternInfo);
const stats = data.stats || {};
const statsMessage = Object.keys(stats).map(key => {
const value = key === 'testPathPattern' ? testPathPattern : config[key];
if (value) {
const matches = pluralize('match', stats[key], 'es');
return ` ${key}: ${chalk.yellow(value)} - ${matches}`;
}
return null;
}).filter(line => line).join('\n');
const statsMessage = Object.keys(stats)
.map(key => {
const value = key === 'testPathPattern' ? testPathPattern : config[key];
if (value) {
const matches = pluralize('match', stats[key], 'es');
return ` ${key}: ${chalk.yellow(value)} - ${matches}`;
}
return null;
})
.filter(line => line)
.join('\n');

return (
chalk.bold('No tests found') + '\n' +
return chalk.bold('No tests found') +
'\n' +
(data.total
? ` ${pluralize('file', data.total || 0, 's')} checked.\n` +
statsMessage
statsMessage
: `No files found in ${config.rootDir}.\n` +
`Make sure Jest's configuration does not exclude this directory.\n` +
`To set up Jest, make sure a package.json file exists.\n` +
`Jest Documentation: facebook.github.io/jest/docs/configuration.html`
)
);
`Make sure Jest's configuration does not exclude this directory.` +
`\nTo set up Jest, make sure a package.json file exists.\n` +
`Jest Documentation: ` +
`facebook.github.io/jest/docs/configuration.html`);
}

getTestPaths(patternInfo: PatternInfo): Promise<SearchResult> {
Expand All @@ -297,9 +288,8 @@ class SearchSource {
const formattedInput = patternInfo.shouldTreatInputAsPattern
? `/${input || ''}/`
: `"${input || ''}"`;
return (input === pattern) ? formattedInput : formattedPattern;
return input === pattern ? formattedInput : formattedPattern;
}

}

module.exports = SearchSource;
15 changes: 8 additions & 7 deletions packages/jest-cli/src/TestNamePatternPrompt.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,14 @@ module.exports = (

const matchedTests = [];

this._cachedTestResults.forEach(({testResults}) => testResults.forEach(({
title,
}) => {
if (regex.test(title)) {
matchedTests.push(title);
}
}));
this._cachedTestResults.forEach(({testResults}) =>
testResults.forEach(({
title,
}) => {
if (regex.test(title)) {
matchedTests.push(title);
}
}));

return matchedTests;
}
Expand Down
52 changes: 27 additions & 25 deletions packages/jest-cli/src/TestRunner.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,7 @@ class TestRunner {
);
aggregatedResults.snapshot.filesRemoved += status.filesRemoved;
aggregatedResults.snapshot.didUpdate = config.updateSnapshot;
aggregatedResults.snapshot.failure =
!!(!aggregatedResults.snapshot.didUpdate &&
aggregatedResults.snapshot.failure = !!(!config.updateSnapshot &&
(aggregatedResults.snapshot.unchecked ||
aggregatedResults.snapshot.unmatched ||
aggregatedResults.snapshot.filesRemoved));
Expand Down Expand Up @@ -269,17 +268,19 @@ class TestRunner {
) {
const mutex = throat(1);
return testPaths.reduce(
(promise, path) => mutex(() => promise
.then(() => {
if (watcher.isInterrupted()) {
throw new CancelRun();
}

this._dispatcher.onTestStart(this._config, path);
return runTest(path, this._config, this._hasteContext.resolver);
})
.then(result => onResult(path, result))
.catch(err => onFailure(path, err))),
(promise, path) =>
mutex(() =>
promise
.then(() => {
if (watcher.isInterrupted()) {
throw new CancelRun();
}

this._dispatcher.onTestStart(this._config, path);
return runTest(path, this._config, this._hasteContext.resolver);
})
.then(result => onResult(path, result))
.catch(err => onFailure(path, err))),
Promise.resolve(),
);
}
Expand All @@ -305,19 +306,20 @@ class TestRunner {

// Send test suites to workers continuously instead of all at once to track
// the start time of individual tests.
const runTestInWorker = ({config, path}) => mutex(() => {
if (watcher.isInterrupted()) {
return Promise.reject();
}
this._dispatcher.onTestStart(config, path);
return worker({
config,
path,
rawModuleMap: watcher.isWatchMode()
? this._hasteContext.moduleMap.getRawModuleMap()
: null,
const runTestInWorker = ({config, path}) =>
mutex(() => {
if (watcher.isInterrupted()) {
return Promise.reject();
}
this._dispatcher.onTestStart(config, path);
return worker({
config,
path,
rawModuleMap: watcher.isWatchMode()
? this._hasteContext.moduleMap.getRawModuleMap()
: null,
});
});
});

const onError = (err, path) => {
onFailure(path, err);
Expand Down
Loading

0 comments on commit fda0a7b

Please sign in to comment.