Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add extra parameter: runTestsByPath. Fixes #4396 #4411

Merged
merged 1 commit into from
Sep 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ exports[`--showConfig outputs config info and exits 1`] = `
\\"nonFlagArgs\\": [],
\\"notify\\": false,
\\"rootDir\\": \\"<<REPLACED_ROOT_DIR>>\\",
\\"runTestsByPath\\": false,
\\"testFailureExitCode\\": 1,
\\"testPathPattern\\": \\"\\",
\\"testResultsProcessor\\": null,
Expand Down
47 changes: 47 additions & 0 deletions integration_tests/__tests__/run_tests_by_path.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/

'use strict';

import runJest from '../runJest';
import {cleanup, writeFiles} from '../utils';
import os from 'os';
import path from 'path';

const skipOnWindows = require('../../scripts/skip_on_windows');
const DIR = path.resolve(os.tmpdir(), 'run_tests_by_path_test');

skipOnWindows.suite();

beforeEach(() => cleanup(DIR));
afterEach(() => cleanup(DIR));

test('runs tests by exact path', () => {
writeFiles(DIR, {
'.watchmanconfig': '',
'__tests__/t1.test.js': 'it("foo", () => {})',
'__tests__/t2.test.js': 'it("bar", () => {})',
'package.json': JSON.stringify({jest: {testEnvironment: 'node'}}),
});

// Passing an exact path executes only the given test.
const run1 = runJest(DIR, ['--runTestsByPath', '__tests__/t1.test.js']);
expect(run1.stderr).toMatch('PASS __tests__/t1.test.js');
expect(run1.stderr).not.toMatch('PASS __tests__/t2.test.js');

// When running with thte flag and a pattern, no test is found.
const run2 = runJest(DIR, ['--runTestsByPath', '__tests__/t']);
expect(run2.stdout).toMatch(/no tests found/i);

// When ran without the flag and a pattern, both tests are found.
const run3 = runJest(DIR, ['__tests__/t']);
expect(run3.stderr).toMatch('PASS __tests__/t1.test.js');
expect(run3.stderr).toMatch('PASS __tests__/t2.test.js');
});
8 changes: 8 additions & 0 deletions packages/jest-cli/src/cli/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,14 @@ const options = {
'rare.',
type: 'boolean',
},
runTestsByPath: {
default: false,
description:
'Used when provided patterns are exact file paths. This avoids ' +
'converting them into a regular expression and matching it against ' +
'every single file.',
type: 'boolean',
},
setupFiles: {
description:
'The paths to modules that run some code to configure or ' +
Expand Down
14 changes: 13 additions & 1 deletion packages/jest-cli/src/get_no_test_found.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ const getNoTestFound = (testRunData, globalConfig): string => {
(current, testRun) => (current += testRun.matches.total),
0,
);
let dataMessage;

if (globalConfig.runTestsByPath) {
dataMessage = `Files: ${globalConfig.nonFlagArgs
.map(p => `"${p}"`)
.join(', ')}`;
} else {
dataMessage = `Pattern: ${chalk.yellow(
globalConfig.testPathPattern,
)} - 0 matches`;
}

return (
chalk.bold('No tests found') +
'\n' +
Expand All @@ -17,7 +29,7 @@ const getNoTestFound = (testRunData, globalConfig): string => {
's',
)}. for more details run with \`--verbose\`` +
'\n' +
`Pattern: ${chalk.yellow(globalConfig.testPathPattern)} - 0 matches`
dataMessage
);
};

Expand Down
14 changes: 13 additions & 1 deletion packages/jest-cli/src/get_no_test_found_verbose.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,24 @@ const getNoTestFoundVerbose = (testRunData, globalConfig): string => {
`Jest Documentation: ` +
`facebook.github.io/jest/docs/configuration.html`;
});
let dataMessage;

if (globalConfig.runTestsByPath) {
dataMessage = `Files: ${globalConfig.nonFlagArgs
.map(p => `"${p}"`)
.join(', ')}`;
} else {
dataMessage = `Pattern: ${chalk.yellow(
globalConfig.testPathPattern,
)} - 0 matches`;
}

return (
chalk.bold('No tests found') +
'\n' +
individualResults.join('\n') +
'\n' +
`Pattern: ${chalk.yellow(globalConfig.testPathPattern)} - 0 matches`
dataMessage
);
};

Expand Down
24 changes: 18 additions & 6 deletions packages/jest-cli/src/reporters/summary_reporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,13 +190,25 @@ class SummaryReporter extends BaseReporter {
);
};

const testInfo = globalConfig.onlyChanged
? chalk.dim(' related to changed files')
: globalConfig.testPathPattern ? getMatchingTestsInfo() : '';
let testInfo = '';

if (globalConfig.runTestsByPath) {
testInfo = chalk.dim(' within paths');
} else if (globalConfig.onlyChanged) {
testInfo = chalk.dim(' related to changed files');
} else if (globalConfig.testPathPattern) {
testInfo = getMatchingTestsInfo();
}

let nameInfo = '';

const nameInfo = globalConfig.testNamePattern
? chalk.dim(' with tests matching ') + `"${globalConfig.testNamePattern}"`
: '';
if (globalConfig.runTestsByPath) {
nameInfo = ' ' + globalConfig.nonFlagArgs.map(p => `"${p}"`).join(', ');
} else if (globalConfig.testNamePattern) {
nameInfo =
chalk.dim(' with tests matching ') +
`"${globalConfig.testNamePattern}"`;
}

const contextInfo =
contexts.size > 1
Expand Down
25 changes: 12 additions & 13 deletions packages/jest-cli/src/run_jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,18 @@ const getTestPaths = async (
) => {
const source = new SearchSource(context);
let data = await source.getTestPaths(globalConfig, changedFilesPromise);
if (!data.tests.length) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol how did that happen

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably me refactoring it last time and giving up on reading all if/else conditions :D

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's because this if is useless.

if (globalConfig.onlyChanged && data.noSCM) {
if (globalConfig.watch) {
data = await source.getTestPaths(globalConfig);
} else {
new Console(outputStream, outputStream).log(
'Jest can only find uncommitted changed files in a git or hg ' +
'repository. If you make your project a git or hg ' +
'repository (`git init` or `hg init`), Jest will be able ' +
'to only run tests related to files changed since the last ' +
'commit.',
);
}

if (!data.tests.length && globalConfig.onlyChanged && data.noSCM) {
if (globalConfig.watch) {
data = await source.getTestPaths(globalConfig);
} else {
new Console(outputStream, outputStream).log(
'Jest can only find uncommitted changed files in a git or hg ' +
'repository. If you make your project a git or hg ' +
'repository (`git init` or `hg init`), Jest will be able ' +
'to only run tests related to files changed since the last ' +
'commit.',
);
}
}
return data;
Expand Down
13 changes: 13 additions & 0 deletions packages/jest-cli/src/search_source.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,17 @@ class SearchSource {
};
}

findTestsByPaths(paths: Array<Path>): SearchResult {
return {
tests: toTests(
this._context,
paths
.map(p => path.resolve(process.cwd(), p))
.filter(this.isTestFilePath.bind(this)),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if it can't find any tests, what does the message look like and does it make sense?

),
};
}

findRelatedTestsFromPattern(paths: Array<Path>): SearchResult {
if (Array.isArray(paths) && paths.length) {
const resolvedPaths = paths.map(p => path.resolve(process.cwd(), p));
Expand Down Expand Up @@ -193,6 +204,8 @@ class SearchSource {
}

return this.findTestRelatedToChangedFiles(changedFilesPromise);
} else if (globalConfig.runTestsByPath && paths && paths.length) {
return Promise.resolve(this.findTestsByPaths(paths));
} else if (globalConfig.findRelatedTests && paths && paths.length) {
return Promise.resolve(this.findRelatedTestsFromPattern(paths));
} else if (globalConfig.testPathPattern != null) {
Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ module.exports = ({
preset: null,
resetMocks: false,
resetModules: false,
runTestsByPath: false,
runner: 'jest-runner',
snapshotSerializers: [],
testEnvironment: 'jest-environment-jsdom',
Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ const getConfigs = (
replname: options.replname,
reporters: options.reporters,
rootDir: options.rootDir,
runTestsByPath: options.runTestsByPath,
silent: options.silent,
testFailureExitCode: options.testFailureExitCode,
testNamePattern: options.testNamePattern,
Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,7 @@ function normalize(options: InitialOptions, argv: Argv) {
case 'resetMocks':
case 'resetModules':
case 'rootDir':
case 'runTestsByPath':
case 'silent':
case 'skipNodeResolution':
case 'testEnvironment':
Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/valid_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ module.exports = ({
resolver: '<rootDir>/resolver.js',
rootDir: '/',
roots: ['<rootDir>'],
runTestsByPath: false,
runner: 'jest-runner',
setupFiles: ['<rootDir>/setup.js'],
setupTestFrameworkScriptFile: '<rootDir>/test_setup_file.js',
Expand Down
1 change: 1 addition & 0 deletions test_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const DEFAULT_GLOBAL_CONFIG: GlobalConfig = {
replname: null,
reporters: [],
rootDir: '/test_root_dir/',
runTestsByPath: false,
silent: false,
testFailureExitCode: 1,
testNamePattern: '',
Expand Down
3 changes: 3 additions & 0 deletions types/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export type DefaultOptions = {|
resetMocks: boolean,
resetModules: boolean,
runner: string,
runTestsByPath: boolean,
snapshotSerializers: Array<Path>,
testEnvironment: string,
testFailureExitCode: string | number,
Expand Down Expand Up @@ -109,6 +110,7 @@ export type InitialOptions = {
rootDir: Path,
roots?: Array<Path>,
runner?: string,
runTestsByPath?: boolean,
scriptPreprocessor?: string,
setupFiles?: Array<Path>,
setupTestFrameworkScriptFile?: Path,
Expand Down Expand Up @@ -167,6 +169,7 @@ export type GlobalConfig = {|
projects: Array<Glob>,
replname: ?string,
reporters: Array<ReporterConfig>,
runTestsByPath: boolean,
rootDir: Path,
silent: boolean,
testFailureExitCode: number,
Expand Down