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

Test glob support #2359

Merged
merged 7 commits into from
Feb 1, 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
17 changes: 16 additions & 1 deletion docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,20 @@ The test environment that will be used for testing. The default environment in J

You can create your own module that will be used for setting up the test environment. The module must export a class with `runScript` and `dispose` methods. See the [node](https://github.com/facebook/jest/blob/master/packages/jest-environment-node/src/index.js) or [jsdom](https://github.com/facebook/jest/blob/master/packages/jest-environment-jsdom/src/index.js) environments as examples.

### `testMatch` [array<string>]
(default: `[ '**/__tests__/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)' ]`)

The glob patterns Jest uses to detect test files. By default it looks for `.js` and `.jsx` files
inside of `__tests__` folders, as well as any files with a suffix of `.test` or `.spec`
(e.g. `Component.test.js` or `Component.spec.js`). It will also find files called `test.js`
or `spec.js`.

See the [micromatch](https://github.com/jonschlinkert/micromatch) package
for details of the patterns you can specify.

See also [`testRegex` [string]](#testregex-string), but note that you
cannot specify both options.

### `testPathDirs` [array<string>]
Default: `["<rootDir>"]`

Expand All @@ -331,7 +345,8 @@ Default: `(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$`
The pattern Jest uses to detect test files. By default it looks for `.js` and `.jsx` files
inside of `__tests__` folders, as well as any files with a suffix of `.test` or `.spec`
(e.g. `Component.test.js` or `Component.spec.js`). It will also find files called `test.js`
or `spec.js`.
or `spec.js`. See also [array<string>]](#testglob-array-string), but note
that you cannot specify both options.

### `testResultsProcessor` [string]
Default: `undefined`
Expand Down
2 changes: 1 addition & 1 deletion examples/typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@
"transform": {
"^.+\\.(ts|tsx)$": "<rootDir>/preprocessor.js"
},
"testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
"testMatch": ["**/__tests__/*.(ts|tsx|js)"]
}
}
2 changes: 1 addition & 1 deletion integration_tests/__tests__/config-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ test('config as JSON', () => {
const result = runJest('verbose_reporter', [
'--config=' + JSON.stringify({
testEnvironment: 'node',
testRegex: 'banana strawbery kiwi',
testMatch: ['banana strawbery kiwi'],
}),
]);
const stdout = result.stdout.toString();
Expand Down
2 changes: 1 addition & 1 deletion integration_tests/typescript-coverage/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"transform": {
"^.+\\.(ts|js)$": "<rootDir>/typescript-preprocessor.js"
},
"testRegex": "/__tests__/.*\\.(ts|tsx|js)$",
"testMatch": ["**/__tests__/*.(ts|tsx|js)"],
"testEnvironment": "node",
"moduleFileExtensions": [
"ts",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,6 @@
"\\.snap$",
"/packages/.*/build"
],
"testRegex": ".*-test\\.js"
"testMatch": ["**/*-test.js"]
}
}
1 change: 1 addition & 0 deletions packages/jest-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"jest-snapshot": "^18.1.0",
"jest-util": "^18.1.0",
"node-notifier": "^5.0.1",
"micromatch": "^2.3.11",
"string-length": "^1.0.1",
"strip-ansi": "^3.0.1",
"throat": "^3.0.0",
Expand Down
29 changes: 25 additions & 4 deletions packages/jest-cli/src/SearchSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@

import type {Config} from 'types/Config';
import type {HasteContext} from 'types/HasteMap';
import type {Path} from 'types/Config';
import type {Glob, Path} from 'types/Config';
import type {ResolveModuleConfig} from 'jest-resolve';

const micromatch = require('micromatch');

const DependencyResolver = require('jest-resolve-dependencies');

const chalk = require('chalk');
Expand All @@ -26,6 +28,7 @@ const {
} = require('jest-util');

type SearchSourceConfig = {
testMatch: Array<Glob>,
testPathDirs: Array<Path>,
testRegex: string,
testPathIgnorePatterns: Array<string>,
Expand Down Expand Up @@ -69,14 +72,32 @@ const pluralize = (
ending: string,
) => `${count} ${word}${count === 1 ? '' : ending}`;

const globsToMatcher = (globs: ?Array<Glob>) => {
if (globs == null || globs.length === 0) {
return () => true;
}

const matchers = globs.map(each => micromatch.matcher(each));
return (path: Path) => matchers.some(each => each(path));
};

const regexToMatcher = (testRegex: string) => {
if (!testRegex) {
return () => true;
}

const regex = new RegExp(pathToRegex(testRegex));
return (path: Path) => regex.test(path);
};

class SearchSource {
_hasteContext: HasteContext;
_config: SearchSourceConfig;
_options: ResolveModuleConfig;
_testPathDirPattern: RegExp;
_testRegex: RegExp;
_testIgnorePattern: ?RegExp;
_testPathCases: {
testMatch: (path: Path) => boolean,
testPathDirs: (path: Path) => boolean,
testRegex: (path: Path) => boolean,
testPathIgnorePatterns: (path: Path) => boolean,
Expand All @@ -98,18 +119,18 @@ class SearchSource {
dir => escapePathForRegex(dir),
).join('|'));

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

this._testPathCases = {
testMatch: globsToMatcher(config.testMatch),
testPathDirs: path => this._testPathDirPattern.test(path),
testPathIgnorePatterns: path => (
!this._testIgnorePattern ||
!this._testIgnorePattern.test(path)
),
testRegex: path => this._testRegex.test(path),
testRegex: regexToMatcher(config.testRegex),
};
}

Expand Down
128 changes: 119 additions & 9 deletions packages/jest-cli/src/__tests__/SearchSource-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const skipOnWindows = require('skipOnWindows');

const rootDir = path.resolve(__dirname, 'test_root');
const testRegex = path.sep + '__testtests__' + path.sep;
const testMatch = ['**/__testtests__/**/*'];
const maxWorkers = 1;

let findMatchingTests;
Expand Down Expand Up @@ -50,10 +51,24 @@ describe('SearchSource', () => {
});
});

it('supports ../ paths and unix separators', () => {
// micromatch doesn't support '..' through the globstar ('**') to avoid
// infinite recursion.

it('supports ../ paths and unix separators via textRegex', () => {
Copy link

Choose a reason for hiding this comment

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

testRegex is not used in this test at all?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good catch, this used to rely on the default, so I've changed it to explicitly set a regex.

if (process.platform !== 'win32') {
const path = '/path/to/__tests__/foo/bar/baz/../../../test.js';
expect(searchSource.isTestFilePath(path)).toEqual(true);
config = normalizeConfig({
name,
rootDir: '.',
testMatch: null,
testPathDirs: [],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$',
});
Runtime.createHasteContext(config, {maxWorkers}).then(hasteMap => {
searchSource = new SearchSource(hasteMap, config);

const path = '/path/to/__tests__/foo/bar/baz/../../../test.js';
expect(searchSource.isTestFilePath(path)).toEqual(true);
});
}
});

Expand All @@ -80,11 +95,12 @@ describe('SearchSource', () => {
);
});

it('finds tests matching a pattern', () => {
it('finds tests matching a pattern via testRegex', () => {
const config = normalizeConfig({
moduleFileExtensions: ['js', 'jsx', 'txt'],
name,
rootDir,
testMatch: null,
testRegex: 'not-really-a-test',
});
return findMatchingTests(config).then(data => {
Expand All @@ -97,11 +113,30 @@ describe('SearchSource', () => {
});
});

it('finds tests matching a JS pattern', () => {
it('finds tests matching a pattern via testMatch', () => {
const config = normalizeConfig({
moduleFileExtensions: ['js', 'jsx', 'txt'],
name,
rootDir,
testMatch: ['**/not-really-a-test.txt'],
testRegex: '',
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
path.relative(rootDir, absPath)
));
expect(relPaths).toEqual([
path.normalize('__testtests__/not-really-a-test.txt'),
]);
});
});

it('finds tests matching a JS regex pattern', () => {
const config = normalizeConfig({
moduleFileExtensions: ['js', 'jsx'],
name,
rootDir,
testMatch: null,
testRegex: 'test\.jsx?',
});
return findMatchingTests(config).then(data => {
Expand All @@ -115,10 +150,30 @@ describe('SearchSource', () => {
});
});

it('finds tests with default file extensions', () => {
it('finds tests matching a JS glob pattern', () => {
const config = normalizeConfig({
moduleFileExtensions: ['js', 'jsx'],
name,
rootDir,
testMatch: ['**/test.js?(x)'],
testRegex: '',
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
path.relative(rootDir, absPath)
));
expect(relPaths.sort()).toEqual([
path.normalize('__testtests__/test.js'),
path.normalize('__testtests__/test.jsx'),
]);
});
});

it('finds tests with default file extensions using testRegex', () => {
const config = normalizeConfig({
name,
rootDir,
testMatch: null,
testRegex,
});
return findMatchingTests(config).then(data => {
Expand All @@ -132,12 +187,30 @@ describe('SearchSource', () => {
});
});

it('finds tests with default file extensions using testMatch', () => {
const config = normalizeConfig({
name,
rootDir,
testMatch,
testRegex: '',
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
path.relative(rootDir, absPath)
));
expect(relPaths.sort()).toEqual([
path.normalize('__testtests__/test.js'),
path.normalize('__testtests__/test.jsx'),
]);
});
});

it('finds tests with similar but custom file extensions', () => {
const config = normalizeConfig({
moduleFileExtensions: ['jsx'],
name,
rootDir,
testRegex,
testMatch,
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
Expand All @@ -154,7 +227,7 @@ describe('SearchSource', () => {
moduleFileExtensions: ['foobar'],
name,
rootDir,
testRegex,
testMatch,
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
Expand All @@ -165,11 +238,30 @@ describe('SearchSource', () => {
]);
});
});

it('finds tests with many kinds of file extensions', () => {
const config = normalizeConfig({
moduleFileExtensions: ['js', 'jsx'],
name,
rootDir,
testMatch,
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
path.relative(rootDir, absPath)
));
expect(relPaths.sort()).toEqual([
path.normalize('__testtests__/test.js'),
path.normalize('__testtests__/test.jsx'),
]);
});
});

it('finds tests using a regex only', () => {
const config = normalizeConfig({
name,
rootDir,
testMatch: null,
testRegex,
});
return findMatchingTests(config).then(data => {
Expand All @@ -182,6 +274,24 @@ describe('SearchSource', () => {
]);
});
});

it('finds tests using a glob only', () => {
const config = normalizeConfig({
name,
rootDir,
testMatch,
testRegex: '',
});
return findMatchingTests(config).then(data => {
const relPaths = data.paths.map(absPath => (
path.relative(rootDir, absPath)
));
expect(relPaths.sort()).toEqual([
path.normalize('__testtests__/test.js'),
path.normalize('__testtests__/test.jsx'),
]);
});
});
});

describe('findRelatedTests', () => {
Expand Down Expand Up @@ -233,7 +343,7 @@ describe('SearchSource', () => {
moduleFileExtensions: ['js', 'jsx', 'foobar'],
name,
rootDir,
testRegex,
testMatch,
});
Runtime.createHasteContext(config, {maxWorkers}).then(hasteMap => {
searchSource = new SearchSource(hasteMap, config);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,13 @@ exports[`testEnvironment throws on invalid environment names 1`] = `
https://facebook.github.io/jest/docs/configuration.html
"
`;

exports[`testMatch throws if testRegex and testMatch are both specified 1`] = `
"● Validation Error:

Configuration options testMatch and testRegex cannot be used together.

Configuration Documentation:
https://facebook.github.io/jest/docs/configuration.html
"
`;
Loading