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

Fix testPathPatterns when config is in subdirectory #14934

Merged
merged 21 commits into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from 10 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
- `[jest-cli]` When specifying paths on the command line, only match against the relative paths of the test files ([#12519](https://github.com/jestjs/jest/pull/12519))
- [**BREAKING**] Changes `testPathPattern` configuration option to `testPathPatterns`, which now takes a list of patterns instead of the regex.
- [**BREAKING**] `--testPathPattern` is now `--testPathPatterns`
- [**BREAKING**] Specifying `testPathPatterns` when programmatically calling `watch` must be specified as `new TestPathPatterns(patterns)`, where `TestPathPatterns` can be imported from `@jest/types`
SimenB marked this conversation as resolved.
Show resolved Hide resolved
- `[jest-reporters, jest-runner]` Unhandled errors without stack get correctly logged to console ([#14619](https://github.com/jestjs/jest/pull/14619))

### Performance
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/executeTestsOnceInMpr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ test('Tests are executed only once even in an MPR', () => {
});
/* eslint-enable sort-keys */

const {stderr, exitCode} = runJest(DIR, ['foo/folder/my-test-bar.js']);
const {stderr, exitCode} = runJest(DIR, ['my-test-bar.js']);

expect(exitCode).toBe(0);

Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/globalSetup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ test('should not call a globalSetup of a project if there are no tests to run fr

const result = runWithJson(e2eDir, [
`--config=${configPath}`,
'--testPathPatterns=project-1',
'--testPathPatterns=setup1',
Copy link
Member

Choose a reason for hiding this comment

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

right, since this is relative to the project config now, and not the global config. I'm afraid this will be quite breaking as well (when using jets projects just to have a single jest command to run from root rather than as a way to isolate test suites), but let's try! 🙂

]);

expect(result.exitCode).toBe(0);
Expand Down
2 changes: 1 addition & 1 deletion e2e/__tests__/globalTeardown.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ test('should not call a globalTeardown of a project if there are no tests to run

const result = runWithJson('global-teardown', [
`--config=${configPath}`,
'--testPathPatterns=project-1',
'--testPathPatterns=teardown1',
]);

expect(result.exitCode).toBe(0);
Expand Down
17 changes: 17 additions & 0 deletions e2e/__tests__/testPathPatternsSubprojects.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {json} from '../runJest';

it('works when specifying --testPathPatterns when config is in subdir', () => {
const {
json: {numTotalTests},
} = json('test-path-patterns-subprojects', [
'--config=config/jest.config.js',
'--testPathPatterns=testA',
]);
expect(numTotalTests).toBe(1);
});
2 changes: 1 addition & 1 deletion e2e/global-setup/setupWithConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
*/

module.exports = function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPatterns);
console.log(globalConfig.testPathPatterns.patterns);
console.log(projectConfig.cache);
};
2 changes: 1 addition & 1 deletion e2e/global-setup/setupWithDefaultExport.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
*/

export default function (globalConfig, projectConfig): void {
console.log(globalConfig.testPathPatterns);
console.log(globalConfig.testPathPatterns.patterns);
console.log(projectConfig.cache);
}
2 changes: 1 addition & 1 deletion e2e/global-teardown/teardownWithConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
*/

module.exports = function (globalConfig, projectConfig) {
console.log(globalConfig.testPathPatterns);
console.log(globalConfig.testPathPatterns.patterns);
console.log(projectConfig.cache);
};
2 changes: 1 addition & 1 deletion e2e/global-teardown/teardownWithDefaultExport.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
*/

export default function (globalConfig, projectConfig): void {
console.log(globalConfig.testPathPatterns);
console.log(globalConfig.testPathPatterns.patterns);
console.log(projectConfig.cache);
}
9 changes: 7 additions & 2 deletions e2e/runJest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import * as fs from 'graceful-fs';
import stripAnsi = require('strip-ansi');
import type {FormattedTestResults} from '@jest/test-result';
import {normalizeIcons} from '@jest/test-utils';
import type {Config} from '@jest/types';
import {type Config, TestPathPatterns} from '@jest/types';
import {ErrorWithStack} from 'jest-util';

const JEST_PATH = path.resolve(__dirname, '../packages/jest-cli/bin/jest.js');
Expand Down Expand Up @@ -284,5 +284,10 @@ export function getConfig(
throw error;
}

return JSON.parse(stdout);
const {testPathPatterns, ...globalConfig} = JSON.parse(stdout);

return {
...globalConfig,
testPathPatterns: new TestPathPatterns(testPathPatterns),
};
}
10 changes: 10 additions & 0 deletions e2e/test-path-patterns-subprojects/config/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

module.exports = {
projects: [{rootDir: 'src'}],
};
1 change: 1 addition & 0 deletions e2e/test-path-patterns-subprojects/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
10 changes: 10 additions & 0 deletions e2e/test-path-patterns-subprojects/src/__tests__/testA.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

it('test', () => {});
10 changes: 10 additions & 0 deletions e2e/test-path-patterns-subprojects/src/__tests__/testB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

it('test', () => {});
10 changes: 10 additions & 0 deletions e2e/test-path-patterns-subprojects/src/__tests__/testC.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

it('test', () => {});
2 changes: 1 addition & 1 deletion packages/jest-cli/src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ export const options: {[key: string]: Options} = {
},
testPathPatterns: {
description:
'A regexp pattern string that is matched against all tests ' +
'An array of regexp pattern strings that are matched against all tests ' +
'paths before executing the test.',
requiresArg: true,
string: true,
Expand Down
12 changes: 6 additions & 6 deletions packages/jest-config/src/__tests__/normalize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1601,7 +1601,7 @@ describe('testPathPatterns', () => {
it('defaults to empty', async () => {
const {options} = await normalize(initialOptions, {} as Config.Argv);

expect(options.testPathPatterns).toEqual([]);
expect(options.testPathPatterns.patterns).toEqual([]);
});

const cliOptions = [
Expand All @@ -1614,22 +1614,22 @@ describe('testPathPatterns', () => {
const argv = {[opt.property]: ['a/b']} as Config.Argv;
const {options} = await normalize(initialOptions, argv);

expect(options.testPathPatterns).toEqual(['a/b']);
expect(options.testPathPatterns.patterns).toEqual(['a/b']);
});

it('ignores invalid regular expressions and logs a warning', async () => {
const argv = {[opt.property]: ['a(']} as Config.Argv;
const {options} = await normalize(initialOptions, argv);

expect(options.testPathPatterns).toEqual([]);
expect(options.testPathPatterns.patterns).toEqual([]);
expect(jest.mocked(console.log).mock.calls[0][0]).toMatchSnapshot();
});

it(`joins multiple ${opt.name} if set`, async () => {
const argv = {[opt.property]: ['a/b', 'c/d']} as Config.Argv;
const {options} = await normalize(initialOptions, argv);

expect(options.testPathPatterns).toEqual(['a/b', 'c/d']);
expect(options.testPathPatterns.patterns).toEqual(['a/b', 'c/d']);
});
});
}
Expand All @@ -1638,15 +1638,15 @@ describe('testPathPatterns', () => {
const argv = {_: [1]} as Config.Argv;
const {options} = await normalize(initialOptions, argv);

expect(options.testPathPatterns).toEqual(['1']);
expect(options.testPathPatterns.patterns).toEqual(['1']);
});

it('joins multiple --testPathPatterns and <regexForTestFiles>', async () => {
const {options} = await normalize(initialOptions, {
_: ['a', 'b'],
testPathPatterns: ['c', 'd'],
} as Config.Argv);
expect(options.testPathPatterns).toEqual(['a', 'b', 'c', 'd']);
expect(options.testPathPatterns.patterns).toEqual(['a', 'b', 'c', 'd']);
});

it('gives precedence to --all', async () => {
Expand Down
21 changes: 7 additions & 14 deletions packages/jest-config/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import merge = require('deepmerge');
import {glob} from 'glob';
import {statSync} from 'graceful-fs';
import micromatch = require('micromatch');
import type {Config} from '@jest/types';
import {type Config, TestPathPatterns} from '@jest/types';
import {replacePathSepForRegex} from 'jest-regex-util';
import Resolver, {
resolveRunner,
Expand All @@ -22,7 +22,6 @@ import Resolver, {
resolveWatchPlugin,
} from 'jest-resolve';
import {
TestPathPatterns,
clearLine,
replacePathSepForGlob,
requireOrImportModule,
Expand Down Expand Up @@ -393,10 +392,7 @@ const normalizeReporters = ({
});
};

const buildTestPathPatterns = (
argv: Config.Argv,
rootDir: string,
): TestPathPatterns => {
const buildTestPathPatterns = (argv: Config.Argv): TestPathPatterns => {
const patterns = [];

if (argv._) {
Expand All @@ -406,12 +402,9 @@ const buildTestPathPatterns = (
patterns.push(...argv.testPathPatterns);
}

const config = {rootDir};
const testPathPatterns = new TestPathPatterns(patterns, config);
const testPathPatterns = new TestPathPatterns(patterns);

try {
testPathPatterns.validate();
} catch {
if (!testPathPatterns.isValid()) {
clearLine(process.stdout);

// eslint-disable-next-line no-console
Expand All @@ -422,7 +415,7 @@ const buildTestPathPatterns = (
),
);

return new TestPathPatterns([], config);
return new TestPathPatterns([]);
}

return testPathPatterns;
Expand Down Expand Up @@ -1012,8 +1005,8 @@ export default async function normalize(
}

newOptions.nonFlagArgs = argv._?.map(arg => `${arg}`);
const testPathPatterns = buildTestPathPatterns(argv, options.rootDir);
newOptions.testPathPatterns = testPathPatterns.patterns;
const testPathPatterns = buildTestPathPatterns(argv);
newOptions.testPathPatterns = testPathPatterns;
newOptions.json = !!argv.json;

newOptions.testFailureExitCode = Number.parseInt(
Expand Down
34 changes: 23 additions & 11 deletions packages/jest-core/src/SearchSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import * as os from 'os';
import * as path from 'path';
import micromatch = require('micromatch');
import type {Test, TestContext} from '@jest/test-result';
import type {Config} from '@jest/types';
import type {Config, TestPathPatternsExecutor} from '@jest/types';
import type {ChangedFiles} from 'jest-changed-files';
import {replaceRootDirInPath} from 'jest-config';
import {escapePathForRegex} from 'jest-regex-util';
import {DependencyResolver} from 'jest-resolve-dependencies';
import {buildSnapshotResolver} from 'jest-snapshot';
import {TestPathPatterns, globsToMatcher} from 'jest-util';
import {globsToMatcher} from 'jest-util';
import type {Filter, Stats, TestPathCases} from './types';

export type SearchResult = {
Expand Down Expand Up @@ -114,7 +114,7 @@ export default class SearchSource {

private _filterTestPathsWithStats(
allPaths: Array<Test>,
testPathPatterns: TestPathPatterns,
testPathPatternsExecutor: TestPathPatternsExecutor,
): SearchResult {
const data: {
stats: Stats;
Expand All @@ -132,9 +132,9 @@ export default class SearchSource {
};

const testCases = [...this._testPathCases]; // clone
if (testPathPatterns.isSet()) {
if (testPathPatternsExecutor.isSet()) {
testCases.push({
isMatch: (path: string) => testPathPatterns.isMatch(path),
isMatch: (path: string) => testPathPatternsExecutor.isMatch(path),
stat: 'testPathPatterns',
});
data.stats.testPathPatterns = 0;
Expand All @@ -155,19 +155,23 @@ export default class SearchSource {
return data;
}

private _getAllTestPaths(testPathPatterns: TestPathPatterns): SearchResult {
private _getAllTestPaths(
testPathPatternsExecutor: TestPathPatternsExecutor,
): SearchResult {
return this._filterTestPathsWithStats(
toTests(this._context, this._context.hasteFS.getAllFiles()),
testPathPatterns,
testPathPatternsExecutor,
);
}

isTestFilePath(path: string): boolean {
return this._testPathCases.every(testCase => testCase.isMatch(path));
}

findMatchingTests(testPathPatterns: TestPathPatterns): SearchResult {
return this._getAllTestPaths(testPathPatterns);
findMatchingTests(
testPathPatternsExecutor: TestPathPatternsExecutor,
): SearchResult {
return this._getAllTestPaths(testPathPatternsExecutor);
}

async findRelatedTests(
Expand Down Expand Up @@ -264,6 +268,7 @@ export default class SearchSource {

private async _getTestPaths(
globalConfig: Config.GlobalConfig,
projectConfig: Config.ProjectConfig,
changedFiles?: ChangedFiles,
): Promise<SearchResult> {
if (globalConfig.onlyChanged) {
Expand Down Expand Up @@ -292,7 +297,9 @@ export default class SearchSource {
);
} else {
return this.findMatchingTests(
TestPathPatterns.fromGlobalConfig(globalConfig),
globalConfig.testPathPatterns.toExecutor({
rootDir: projectConfig.rootDir,
}),
);
}
}
Expand Down Expand Up @@ -321,10 +328,15 @@ export default class SearchSource {

async getTestPaths(
globalConfig: Config.GlobalConfig,
projectConfig: Config.ProjectConfig,
changedFiles?: ChangedFiles,
filter?: Filter,
): Promise<SearchResult> {
const searchResult = await this._getTestPaths(globalConfig, changedFiles);
const searchResult = await this._getTestPaths(
globalConfig,
projectConfig,
changedFiles,
);

const filterPath = globalConfig.filter;

Expand Down
Loading
Loading