Skip to content

Commit

Permalink
Remove mocksPattern, rename testPathDirs to roots. (jestjs#2776)
Browse files Browse the repository at this point in the history
* Remove mocksPattern config.

* Rename `testPathDirs` to `roots`.

* Fix mocks pattern.
  • Loading branch information
cpojer authored Feb 7, 2017
1 parent 482135a commit ba7cba4
Show file tree
Hide file tree
Showing 18 changed files with 70 additions and 60 deletions.
21 changes: 9 additions & 12 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,6 @@ For example, the following would create a global `__DEV__` variable set to `true

Note that, if you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will *not* be persisted across test runs for other test files.

### `mocksPattern` [string]
Default: `(?:[\\/]|^)__mocks__[\\/]`

A pattern that is matched against file paths to determine which folder contains manual mocks.

### `moduleFileExtensions` [array<string>]
Default: `["js", "json", "jsx", "node"]`

Expand Down Expand Up @@ -232,6 +227,15 @@ Oftentimes, you'll want to set this to `'src'` or `'lib'`, corresponding to wher

*Note that using `'<rootDir>'` as a string token in any other path-based config settings will refer back to this value. So, for example, if you want your [`setupFiles`](#setupfiles-array) config entry to point at the `env-setup.js` file at the root of your project, you could set its value to `["<rootDir>/env-setup.js"]`.*

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

A list of paths to directories that Jest should use to search for files in.

There are times where you only want Jest to search in a single sub-directory (such as cases where you have a `src/` directory in your repo), but prevent it from accessing the rest of the repo.

*Note: While `rootDir` is mostly used as a token to be re-used in other configuration options, `roots` is used by the internals of Jest to locate **test files and source files**. By default, `roots` has a single entry `<rootDir>` but there are cases where you want to have multiple roots within one project, for example `roots: ["<rootDir>/src/", "<rootDir>/tests/"]`.*

### `setupFiles` [array]
Default: `[]`

Expand Down Expand Up @@ -330,13 +334,6 @@ 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>"]`

A list of paths to directories that Jest should use to search for tests in.

There are times where you only want Jest to search in a single sub-directory (such as cases where you have a `src/` directory in your repo), but not the rest of the repo.

### `testPathIgnorePatterns` [array<string>]
Default: `["/node_modules/"]`

Expand Down
14 changes: 7 additions & 7 deletions packages/jest-cli/src/SearchSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ const {
} = require('jest-util');

type SearchSourceConfig = {
roots: Array<Path>,
testMatch: Array<Glob>,
testPathDirs: Array<Path>,
testRegex: string,
testPathIgnorePatterns: Array<string>,
};
Expand Down Expand Up @@ -94,11 +94,11 @@ class SearchSource {
_hasteContext: HasteContext;
_config: SearchSourceConfig;
_options: ResolveModuleConfig;
_testPathDirPattern: RegExp;
_rootPattern: RegExp;
_testIgnorePattern: ?RegExp;
_testPathCases: {
roots: (path: Path) => boolean,
testMatch: (path: Path) => boolean,
testPathDirs: (path: Path) => boolean,
testRegex: (path: Path) => boolean,
testPathIgnorePatterns: (path: Path) => boolean,
};
Expand All @@ -114,8 +114,8 @@ class SearchSource {
skipNodeResolution: false,
};

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

Expand All @@ -124,8 +124,8 @@ class SearchSource {
ignorePattern.length ? new RegExp(ignorePattern.join('|')) : null;

this._testPathCases = {
roots: path => this._rootPattern.test(path),
testMatch: globsToMatcher(config.testMatch),
testPathDirs: path => this._testPathDirPattern.test(path),
testPathIgnorePatterns: path => (
!this._testIgnorePattern ||
!this._testIgnorePattern.test(path)
Expand Down Expand Up @@ -212,7 +212,7 @@ class SearchSource {
}

findChangedTests(options: Options): Promise<SearchResult> {
return Promise.all(this._config.testPathDirs.map(determineSCM))
return Promise.all(this._config.roots.map(determineSCM))
.then(repos => {
if (!repos.every(([gitRepo, hgRepo]) => gitRepo || hgRepo)) {
return {
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-cli/src/__tests__/SearchSource-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('SearchSource', () => {
config = normalizeConfig({
name,
rootDir: '.',
testPathDirs: [],
roots: [],
});
Runtime.createHasteContext(config, {maxWorkers}).then(hasteMap => {
searchSource = new SearchSource(hasteMap, config);
Expand All @@ -59,8 +59,8 @@ describe('SearchSource', () => {
config = normalizeConfig({
name,
rootDir: '.',
roots: [],
testMatch: null,
testPathDirs: [],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$',
});
Runtime.createHasteContext(config, {maxWorkers}).then(hasteMap => {
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-cli/src/__tests__/watch-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe('Watch mode flows', () => {
hasteMap = {on: () => {}};
argv = {};
hasteContext = {};
config = {testPathDirs: [], testPathIgnorePatterns: [], testRegex: ''};
config = {roots: [], testPathIgnorePatterns: [], testRegex: ''};
stdin = new MockStdin();
});

Expand Down Expand Up @@ -99,7 +99,7 @@ describe('Watch mode flows', () => {
stdin.emit(KEYS.U);

expect(runJestMock.mock.calls[0][1]).toEqual({
testPathDirs: [],
roots: [],
testPathIgnorePatterns: [],
testRegex: '',
updateSnapshot: true,
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-cli/src/lib/__tests__/logDebugMessages-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ describe('logDebugMessages', () => {
logDebugMessages({
automock: false,
rootDir: '/path/to/dir',
testPathDirs: ['path/to/dir/test'],
roots: ['path/to/dir/test'],
testRunner: 'myRunner',
watch: true,
}, pipe);
expect(pipe.write).toHaveBeenCalledWith(
`config = {
"automock": false,
"rootDir": "/path/to/dir",
"testPathDirs": [
"roots": [
"path/to/dir/test"
],
"testRunner": "myRunner",
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/__tests__/normalize-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,8 @@ function testPathArray(key) {
});
}

describe('testPathDirs', () => {
testPathArray('testPathDirs');
describe('roots', () => {
testPathArray('roots');
});

describe('transform', () => {
Expand Down
3 changes: 1 addition & 2 deletions packages/jest-config/src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ module.exports = ({
haste: {
providesModuleNodeModules: [],
},
mocksPattern: '__mocks__',
moduleDirectories: ['node_modules'],
moduleFileExtensions: [
'js',
Expand All @@ -46,13 +45,13 @@ module.exports = ({
preset: null,
resetMocks: false,
resetModules: false,
roots: ['<rootDir>'],
snapshotSerializers: [],
testEnvironment: 'jest-environment-jsdom',
testMatch: [
'**/__tests__/**/*.js?(x)',
'**/?(*.)(spec|test).js?(x)',
],
testPathDirs: ['<rootDir>'],
testPathIgnorePatterns: [NODE_MODULES_REGEXP],
testRegex: '',
testResultsProcessor: null,
Expand Down
11 changes: 11 additions & 0 deletions packages/jest-config/src/deprecated.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ const deprecatedOptions = {
}
Please update your configuration.`,

testPathDirs: (config: Object) =>
` Option ${chalk.bold('"testPathDirs"')} was replaced by ${chalk.bold('"roots"')}.
Jest now treats your current configuration as:
{
${chalk.bold('"roots"')}: ${chalk.bold(format(config.testPathDirs))}
}
Please update your configuration.
`,
};
/* eslint-enable max-len */

Expand Down
6 changes: 4 additions & 2 deletions packages/jest-config/src/normalize.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ function normalize(config: InitialConfig, argv: Object = {}) {
if (config.testEnvironment) {
config.testEnvironment = getTestEnvironment(config);
}
if (!config.roots && config.testPathDirs) {
config.roots = config.testPathDirs;
}

const babelJest = setupBabelJest(config);
const newConfig = Object.assign({}, DEFAULT_CONFIG);
Expand All @@ -273,7 +276,7 @@ function normalize(config: InitialConfig, argv: Object = {}) {
//$FlowFixMe
value = config[key].map(resolve.bind(null, config.rootDir, key));
break;
case 'testPathDirs':
case 'roots':
//$FlowFixMe
value = config[key].map(filePath => path.resolve(
config.rootDir,
Expand Down Expand Up @@ -331,7 +334,6 @@ function normalize(config: InitialConfig, argv: Object = {}) {
case 'haste':
case 'logHeapUsage':
case 'logTransformErrors':
case 'mocksPattern':
case 'moduleDirectories':
case 'moduleFileExtensions':
case 'moduleLoader':
Expand Down
3 changes: 1 addition & 2 deletions packages/jest-config/src/validConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ module.exports = ({
},
logHeapUsage: true,
logTransformErrors: true,
mocksPattern: '__mocks__',
moduleDirectories: ['node_modules'],
moduleFileExtensions: ['js', 'json', 'jsx', 'node'],
moduleLoader: '<rootDir>',
Expand All @@ -60,14 +59,14 @@ module.exports = ({
resetMocks: false,
resetModules: false,
rootDir: '/',
roots: ['<rootDir>'],
setupFiles: ['<rootDir>/setup.js'],
setupTestFrameworkScriptFile: '<rootDir>/testSetupFile.js',
silent: true,
snapshotSerializers: ['my-serializer-module'],
testEnvironment: 'jest-environment-jsdom',
testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)'],
testNamePattern: 'test signature',
testPathDirs: ['<rootDir>'],
testPathIgnorePatterns: [NODE_MODULES_REGEXP],
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$',
testResultsProcessor: 'processor-node-module',
Expand Down
12 changes: 7 additions & 5 deletions packages/jest-editor-support/src/parsers/BabylonParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ const babylonParser = (file: string) => {
const babelRC = getBabelRC(file, {useCache: true});
const babel = JSON.parse(babelRC);

const plugins = Array.isArray(babel.plugins) ? babel.plugins.concat(['flow']) : ['flow'];
const plugins = Array.isArray(babel.plugins)
? babel.plugins.concat(['flow'])
: ['flow'];
const config = {plugins, sourceType: 'module'};
const ast = babylon.parse(data, config);

Expand All @@ -63,7 +65,7 @@ const babylonParser = (file: string) => {
block.name = node.expression.arguments[0].value;
block.start = node.loc.start;
block.end = node.loc.end;

block.start.column += 1;

block.file = file;
Expand All @@ -72,7 +74,7 @@ const babylonParser = (file: string) => {

// An `expect` was found in the AST
// So take the AST node and create an object for us
// to store for later usage
// to store for later usage
const foundExpectNode = (node: any, file: string) => {
const expect = new Expect();
expect.start = node.loc.start;
Expand Down Expand Up @@ -147,7 +149,7 @@ const babylonParser = (file: string) => {
if (!root.body.hasOwnProperty(node)) {
return;
}

// Pull out the node
const element = root.body[node];

Expand All @@ -173,7 +175,7 @@ const babylonParser = (file: string) => {
.filter(argument => isFunctionDeclaration(argument.type))
.forEach(argument => searchNodes(argument.body, file));
}

if (isFunctionCall(element)) {
element.expression.arguments
.filter(argument => isFunctionDeclaration(argument.type))
Expand Down
6 changes: 3 additions & 3 deletions packages/jest-haste-map/src/getMockName.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@

const path = require('path');

const mocksPattern = '__mocks__';
const MOCKS_PATTERN = path.sep + '__mocks__' + path.sep;

const getMockName = (filePath: string) => {
const mockPath = filePath.split(mocksPattern)[1];
return mockPath.substring(1, mockPath.lastIndexOf(path.extname(mockPath)));
const mockPath = filePath.split(MOCKS_PATTERN)[1];
return mockPath.substring(0, mockPath.lastIndexOf(path.extname(mockPath)));
};

module.exports = getMockName;
6 changes: 5 additions & 1 deletion packages/jest-runtime/src/__tests__/transform-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ const skipOnWindows = require('skipOnWindows');
jest
.mock('graceful-fs')
.mock('jest-file-exists')
.mock('jest-util')
.mock('jest-util', () => {
const util = require.requireActual('jest-util');
util.createDirectory = jest.fn();
return util;
})
.mock('vm');

jest.mock(
Expand Down
8 changes: 3 additions & 5 deletions packages/jest-runtime/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const shouldInstrument = require('./shouldInstrument');
const transform = require('./transform');
const {
createDirectory,
escapePathForRegex,
} = require('jest-util');

type Module = {|
Expand Down Expand Up @@ -81,7 +82,6 @@ class Runtime {
_mockFactories: {[key: string]: () => any};
_mockMetaDataCache: {[key: string]: MockFunctionMetadata};
_mockRegistry: {[key: string]: any};
_mocksPattern: ?RegExp;
_moduleMocker: ModuleMocker;
_moduleRegistry: {[key: string]: Module};
_internalModuleRegistry: {[key: string]: Module};
Expand Down Expand Up @@ -110,8 +110,6 @@ class Runtime {
this._explicitShouldMock = Object.create(null);
this._isCurrentlyExecutingManualMock = null;
this._mockFactories = Object.create(null);
this._mocksPattern =
config.mocksPattern ? new RegExp(config.mocksPattern) : null;
this._shouldAutoMock = config.automock;
this._virtualMocks = Object.create(null);

Expand Down Expand Up @@ -204,13 +202,13 @@ class Runtime {
extensions: [SNAPSHOT_EXTENSION].concat(config.moduleFileExtensions),
ignorePattern,
maxWorkers: (options && options.maxWorkers) || 1,
mocksPattern: config.mocksPattern,
mocksPattern: escapePathForRegex(path.sep + '__mocks__' + path.sep),
name: config.name,
platforms: config.haste.platforms || ['ios', 'android'],
providesModuleNodeModules: config.haste.providesModuleNodeModules,
resetCache: options && options.resetCache,
retainAllFiles: false,
roots: config.testPathDirs,
roots: config.roots,
useWatchman: config.watchman,
watch: options && options.watch,
});
Expand Down
6 changes: 5 additions & 1 deletion packages/jest-runtime/src/shouldInstrument.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@

import type {Config, Path} from 'types/Config';

const {escapePathForRegex} = require('jest-util');
const micromatch = require('micromatch');
const path = require('path');

const MOCKS_PATTERN =
new RegExp(escapePathForRegex(path.sep + '__mocks__' + path.sep));

const shouldInstrument = (filename: Path, config: Config): boolean => {
if (!config.collectCoverage) {
return false;
Expand Down Expand Up @@ -58,7 +62,7 @@ const shouldInstrument = (filename: Path, config: Config): boolean => {
return false;
}

if (config.mocksPattern && filename.match(config.mocksPattern)) {
if (MOCKS_PATTERN.test(filename)) {
return false;
}

Expand Down
Loading

0 comments on commit ba7cba4

Please sign in to comment.