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

chore: types #8430

Closed
wants to merge 15 commits into from
Closed
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"slash": "^2.0.0",
"string-length": "^2.0.0",
"strip-ansi": "^5.0.0",
"typescript": "^3.4.1",
"typescript": "^3.4.5",
"webpack": "^4.28.4"
},
"scripts": {
Expand Down
4 changes: 1 addition & 3 deletions packages/jest-config/src/ValidConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const NODE_MODULES_REGEXP = replacePathSepForRegex(NODE_MODULES);

const initialOptions: Config.InitialOptions = {
automock: false,
// @ts-ignore TODO: type this properly
bail: multipleValidOptions(false, 0),
browser: false,
cache: true,
Expand All @@ -39,9 +38,8 @@ const initialOptions: Config.InitialOptions = {
},
},
dependencyExtractor: '<rootDir>/dependencyExtractor.js',
// @ts-ignore TODO: type this properly
displayName: multipleValidOptions('test-config', {
color: 'blue',
color: 'blue' as 'blue',
name: 'test-config',
}),
errorOnDeprecated: false,
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-config/src/__tests__/readConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ test('readConfig() throws when an object is passed without a file path', () => {
readConfig(
// @ts-ignore
null /* argv */,
{} /* packageRootOrConfig */,
<any>{} /* packageRootOrConfig */,
false /* skipArgvConfigOption */,
null /* parentConfigPath */,
);
Expand Down
4 changes: 2 additions & 2 deletions packages/jest-config/src/getMaxWorkers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export default function getMaxWorkers(
return 1;
} else if (argv.maxWorkers) {
// TODO: How to type this properly? Should probably use `coerce` from `yargs`
const maxWorkers = (argv.maxWorkers as unknown) as number | string;
const parsed = parseInt(maxWorkers as string, 10);
const maxWorkers = argv.maxWorkers;
const parsed = parseInt(<string>maxWorkers, 10);

if (
typeof maxWorkers === 'string' &&
Expand Down
21 changes: 13 additions & 8 deletions packages/jest-config/src/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -659,14 +659,19 @@ export default function normalize(
? _replaceRootDirTags(options.rootDir, project)
: project,
)
.reduce((projects, project) => {
// Project can be specified as globs. If a glob matches any files,
// We expand it to these paths. If not, we keep the original path
// for the future resolution.
const globMatches =
typeof project === 'string' ? glob.sync(project) : [];
return projects.concat(globMatches.length ? globMatches : project);
}, []);
.reduce(
(projects, project) => {
// Project can be specified as globs. If a glob matches any files,
// We expand it to these paths. If not, we keep the original path
// for the future resolution.
const globMatches =
typeof project === 'string' ? glob.sync(project) : [];
return projects.concat(
globMatches.length ? globMatches : project,
);
},
<Array<string>>[],
);
break;
case 'moduleDirectories':
case 'testMatch':
Expand Down
55 changes: 35 additions & 20 deletions packages/jest-config/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const resolve = (
);
}

return module;
return module as string;
};

export const escapeGlobCharacters = (path: Config.Path): Config.Glob =>
Expand All @@ -69,26 +69,35 @@ export const replaceRootDirInPath = (
);
};

// TODO: Type as returning same type as input
const _replaceRootDirInObject = (
type ReplaceRootDirTagsObject = {[key: string]: unknown};

type ReplaceRootDirTagsValue =
| RegExp
| ReplaceRootDirTagsObject
| Array<ReplaceRootDirTagsObject>
| string
| null;

interface ReplaceRootDirTags {
<T>(rootDir: Config.Path, config: T): T;
(
rootDir: Config.Path,
config: ReplaceRootDirTagsObject,
): ReplaceRootDirTagsObject;
(rootDir: Config.Path, config: RegExp): RegExp;
(rootDir: Config.Path, config: Array<ReplaceRootDirTagsObject>): Array<
ReplaceRootDirTagsObject
>;
(rootDir: Config.Path, config: string): string;
}

export const _replaceRootDirTags: ReplaceRootDirTags = (
rootDir: Config.Path,
config: any,
): {[key: string]: unknown} => {
if (config !== null) {
const newConfig: {[key: string]: unknown} = {};
for (const configKey in config) {
newConfig[configKey] =
configKey === 'rootDir'
? config[configKey]
: _replaceRootDirTags(rootDir, config[configKey]);
}
return newConfig;
config: ReplaceRootDirTagsValue,
): any => {
if (config == null) {
return config;
}
return config;
};

// TODO: Type as returning same type as input
export const _replaceRootDirTags = (rootDir: Config.Path, config: any): any => {
switch (typeof config) {
case 'object':
if (Array.isArray(config)) {
Expand All @@ -97,7 +106,13 @@ export const _replaceRootDirTags = (rootDir: Config.Path, config: any): any => {
if (config instanceof RegExp) {
return config;
}
return _replaceRootDirInObject(rootDir, config);
if ('rootDir' in config) {
return {
...config,
...{rootDir: _replaceRootDirTags(rootDir, config['rootDir'])},
};
}
return config;
case 'string':
return replaceRootDirInPath(rootDir, config);
}
Expand Down
102 changes: 55 additions & 47 deletions packages/jest-core/src/runGlobalHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@
*/

import {extname} from 'path';
import pEachSeries from 'p-each-series';
import {addHook} from 'pirates';
import {Config} from '@jest/types';
import {Test} from 'jest-runner';
import {ScriptTransformer} from '@jest/transform';
import {interopRequireDefault} from 'jest-util';

// Needed , revert to normal import when drop node 6 and upgrade p-each-series 2.1.0
const pEachSeries = require('p-each-series') as <ValueType>(
input: Iterable<PromiseLike<ValueType> | ValueType>,
iterator: (element: ValueType, index: number) => unknown,
) => Promise<Array<ValueType>>;

export default async ({
allTests,
globalConfig,
Expand All @@ -31,63 +36,66 @@ export default async ({
}

if (globalModulePaths.size > 0) {
await pEachSeries(Array.from(globalModulePaths), async modulePath => {
if (!modulePath) {
return;
}
await pEachSeries(
Array.from(globalModulePaths),
async (modulePath: string | null | undefined) => {
if (!modulePath) {
return;
}

const correctConfig = allTests.find(
t => t.context.config[moduleName] === modulePath,
);
const correctConfig = allTests.find(
t => t.context.config[moduleName] === modulePath,
);

const projectConfig = correctConfig
? correctConfig.context.config
: // Fallback to first config
allTests[0].context.config;
const projectConfig = correctConfig
? correctConfig.context.config
: // Fallback to first config
allTests[0].context.config;

const transformer = new ScriptTransformer(projectConfig);
const transformer = new ScriptTransformer(projectConfig);

// Load the transformer to avoid a cycle where we need to load a
// transformer in order to transform it in the require hooks
transformer.preloadTransformer(modulePath);
// Load the transformer to avoid a cycle where we need to load a
// transformer in order to transform it in the require hooks
transformer.preloadTransformer(modulePath);

let transforming = false;
const revertHook = addHook(
(code, filename) => {
try {
transforming = true;
return (
transformer.transformSource(filename, code, false).code || code
);
} finally {
transforming = false;
}
},
{
exts: [extname(modulePath)],
ignoreNodeModules: false,
matcher: (...args) => {
if (transforming) {
// Don't transform any dependency required by the transformer itself
return false;
let transforming = false;
const revertHook = addHook(
(code, filename) => {
try {
transforming = true;
return (
transformer.transformSource(filename, code, false).code || code
);
} finally {
transforming = false;
}
return transformer.shouldTransform(...args);
},
},
);
{
exts: [extname(modulePath)],
ignoreNodeModules: false,
matcher: (...args) => {
if (transforming) {
// Don't transform any dependency required by the transformer itself
return false;
}
return transformer.shouldTransform(...args);
},
},
);

const globalModule = interopRequireDefault(require(modulePath)).default;
const globalModule = interopRequireDefault(require(modulePath)).default;

if (typeof globalModule !== 'function') {
throw new TypeError(
`${moduleName} file must export a function at ${modulePath}`,
);
}
if (typeof globalModule !== 'function') {
throw new TypeError(
`${moduleName} file must export a function at ${modulePath}`,
);
}

await globalModule(globalConfig);
await globalModule(globalConfig);

revertHook();
});
revertHook();
},
);
}

return Promise.resolve();
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-types/src/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ export type Argv = Arguments<
json: boolean;
lastCommit: boolean;
logHeapUsage: boolean;
maxWorkers: number;
maxWorkers: number | string; // Via getMaxWorkers parses strings such as (50%)
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleNameMapper: string;
Expand Down
5 changes: 2 additions & 3 deletions packages/jest-validate/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,11 @@
"camelcase": "^5.0.0",
"chalk": "^2.0.1",
"jest-get-type": "^24.8.0",
"leven": "^2.1.0",
"leven": "^3.1.0",
"pretty-format": "^24.8.0"
},
"devDependencies": {
"@types/camelcase": "^4.1.0",
"@types/leven": "^2.1.1"
"@types/camelcase": "^4.1.0"
},
"engines": {
"node": ">= 6"
Expand Down
8 changes: 4 additions & 4 deletions packages/jest-validate/src/condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ export function validationCondition(option: any, validOption: any): boolean {
return getValues(validOption).some(e => validationConditionSingle(option, e));
}

// TODO: This should infer the types of its arguments, and return a union type of the types
// See https://github.com/Microsoft/TypeScript/issues/5453
export function multipleValidOptions(...args: Array<any>) {
const options = [...args];
export function multipleValidOptions<T extends Array<any>>(
...args: T
): T[number] {
const options = <T>[...args];
// @ts-ignore
options[MULTIPLE_VALID_OPTIONS_SYMBOL] = true;
return options;
Expand Down
Loading