Skip to content

Commit

Permalink
fix a couple more type errors
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Feb 27, 2019
1 parent 7b38a4a commit e48cd88
Show file tree
Hide file tree
Showing 11 changed files with 126 additions and 63 deletions.
35 changes: 21 additions & 14 deletions packages/jest-core/src/SearchSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ import {escapePathForRegex} from 'jest-regex-util';
import {replaceRootDirInPath} from 'jest-config';
import {buildSnapshotResolver} from 'jest-snapshot';
import {replacePathSepForGlob, testPathPatternToRegExp} from 'jest-util';
import {Stats, TestPathCases, TestPathCasesWithPathPattern} from './types';

type SearchResult = {
noSCM?: boolean;
stats?: {[key: string]: number};
stats?: Stats;
collectCoverageFrom?: Set<string>;
tests: Array<Test>;
total?: number;
Expand All @@ -40,14 +41,6 @@ type FilterResult = {
message: string;
};

type TestPathCases = {
roots: (path: Config.Path) => boolean;
testMatch: (path: Config.Path) => boolean;
testRegex: (path: Config.Path) => boolean;
testPathIgnorePatterns: (path: Config.Path) => boolean;
testPathPattern?: (path: Config.Path) => boolean;
};

const globsToMatcher = (globs?: Array<Config.Glob> | null) => {
if (globs == null || globs.length === 0) {
return () => true;
Expand Down Expand Up @@ -105,27 +98,34 @@ export default class SearchSource {
testPathPattern?: string,
): SearchResult {
const data: {
stats: {[key in keyof TestPathCases]: number};
stats: Stats;
tests: Array<Test>;
total: number;
} = {
stats: {},
stats: {
roots: 0,
testMatch: 0,
testPathIgnorePatterns: 0,
testRegex: 0,
},
tests: [],
total: allPaths.length,
};

const testCases = Object.assign({}, this._testPathCases);
if (testPathPattern) {
const regex = testPathPatternToRegExp(testPathPattern);
testCases.testPathPattern = (path: Config.Path) => regex.test(path);
(testCases as TestPathCasesWithPathPattern).testPathPattern = (
path: Config.Path,
) => regex.test(path);
}

const testCasesKeys = Object.keys(testCases) as Array<keyof TestPathCases>;
const testCasesKeys = Object.keys(testCases) as Array<keyof Stats>;
data.tests = allPaths.filter(test =>
testCasesKeys.reduce((flag, key) => {
if (testCases[key](test.path)) {
if (data.stats[key] === undefined) {
data.stats[key] = 1;
data.stats[key] = 0;
}
++data.stats[key]!;
return flag && true;
Expand All @@ -135,6 +135,13 @@ export default class SearchSource {
}, true),
);

// TODO: Is this necessary? Done to keep the object the same as before the TS migration
testCasesKeys.forEach(key => {
if (data.stats[key] === 0) {
delete data.stats[key];
}
});

return data;
}

Expand Down
6 changes: 3 additions & 3 deletions packages/jest-core/src/SnapshotInteractiveMode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ const {ARROW, CLEAR} = specialChars;
export default class SnapshotInteractiveMode {
private _pipe: NodeJS.WritableStream;
private _isActive: boolean;
private _updateTestRunnerConfig: (
private _updateTestRunnerConfig!: (
assertion: TestResult.AssertionLocation | null,
shouldUpdateSnapshot: boolean,
) => unknown;
private _testAssertions: Array<TestResult.AssertionLocation>;
private _countPaths: number;
private _testAssertions!: Array<TestResult.AssertionLocation>;
private _countPaths!: number;
private _skippedNum: number;

constructor(pipe: NodeJS.WritableStream) {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-core/src/getNoTestFound.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function getNoTestFound(
globalConfig: Config.GlobalConfig,
): string {
const testFiles = testRunData.reduce(
(current, testRun) => current + testRun.matches.total || 0,
(current, testRun) => current + (testRun.matches.total || 0) || 0,
0,
);
let dataMessage;
Expand Down
9 changes: 5 additions & 4 deletions packages/jest-core/src/getNoTestFoundVerbose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,25 @@
import chalk from 'chalk';
import {Config} from '@jest/types';
import pluralize from './pluralize';
import {TestRunData} from './types';
import {Stats, TestRunData} from './types';

export default function getNoTestFoundVerbose(
testRunData: TestRunData,
globalConfig: Config.GlobalConfig,
): string {
const individualResults = testRunData.map(testRun => {
const stats = testRun.matches.stats || {};
const stats = testRun.matches.stats || ({} as Stats);
const config = testRun.context.config;
const statsMessage = Object.keys(stats)
const statsMessage = (Object.keys(stats) as Array<keyof Stats>)
.map(key => {
if (key === 'roots' && config.roots.length === 1) {
return null;
}
const value = config[key];
if (value) {
const valueAsString = Array.isArray(value) ? value.join(', ') : value;
const matches = pluralize('match', stats[key], 'es');
return ` ${key}: ${chalk.yellow(value)} - ${matches}`;
return ` ${key}: ${chalk.yellow(valueAsString)} - ${matches}`;
}
return null;
})
Expand Down
1 change: 1 addition & 0 deletions packages/jest-core/src/lib/update_global_config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export default (
newConfig.coverageReporters = options.coverageReporters;
}

// @ts-ignore: does it make sense to be able to set this?
if (options.noSCM) {
newConfig.noSCM = true;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/jest-core/src/plugins/quit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ class QuitPlugin extends BaseWatchPlugin {
}

async run() {
// @ts-ignore
if (typeof this._stdin.setRawMode === 'function') {
// @ts-ignore
this._stdin.setRawMode(false);
}
this._stdout.write('\n');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import {BaseWatchPlugin, JestHookSubscriber} from 'jest-watcher';
import SnapshotInteractiveMode from '../SnapshotInteractiveMode';

class UpdateSnapshotInteractivePlugin extends BaseWatchPlugin {
_snapshotInteractiveMode: SnapshotInteractiveMode;
_failedSnapshotTestPaths: Array<unknown>;
_failedSnapshotTestAssertions: Array<TestResult.AssertionLocation>;
private _snapshotInteractiveMode: SnapshotInteractiveMode;
private _failedSnapshotTestAssertions: Array<TestResult.AssertionLocation>;
isInternal: true;

constructor(options: {
Expand Down
25 changes: 23 additions & 2 deletions packages/jest-core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,34 @@

import {Context} from 'jest-runtime';
import {Test} from 'jest-runner';
import {TestResult} from '@jest/types';
import {Config, TestResult} from '@jest/types';

export type TestRunData = Array<{
context: Context;
matches: {allTests: number; tests: Array<Test>; total?: number};
matches: {
allTests: number;
tests: Array<Test>;
total?: number;
stats?: Stats;
};
}>;

export type Stats = Record<
keyof (TestPathCases | TestPathCasesWithPathPattern),
number
>;

export type TestPathCases = {
roots: (path: Config.Path) => boolean;
testMatch: (path: Config.Path) => boolean;
testPathIgnorePatterns: (path: Config.Path) => boolean;
testRegex: (path: Config.Path) => boolean;
};

export type TestPathCasesWithPathPattern = TestPathCases & {
testPathPattern: (path: Config.Path) => boolean;
};

// TODO: Obtain this from @jest/reporters once its been migrated
export type ReporterOnStartOptions = {
estimatedTime: number;
Expand Down
77 changes: 48 additions & 29 deletions packages/jest-core/src/watch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import ansiEscapes from 'ansi-escapes';
import chalk from 'chalk';
import exit from 'exit';
import HasteMap from 'jest-haste-map';
import HasteMap, {HasteChangeEvent} from 'jest-haste-map';
import {formatExecError} from 'jest-message-util';
import {isInteractive, preRunMessage, specialChars} from 'jest-util';
// @ts-ignore: Not migrated to TS
Expand All @@ -35,6 +35,15 @@ import {
} from './lib/watch_plugins_helpers';
import activeFilters from './lib/active_filters_message';

type ReservedInfo = {
forbiddenOverwriteMessage?: string;
key?: string;
overwritable: boolean;
plugin: WatchPlugin;
};

type WatchPluginKeysMap = Map<string, ReservedInfo>;

const {print: preRunMessagePrint} = preRunMessage;

let hasExitListener = false;
Expand All @@ -47,16 +56,20 @@ const INTERNAL_PLUGINS = [
QuitPlugin,
];

const RESERVED_KEY_PLUGINS = new Map([
// TODO: Is it correct with constructor here?
const RESERVED_KEY_PLUGINS = new Map<
WatchPlugin,
{forbiddenOverwriteMessage: string; key?: string}
>([
[
UpdateSnapshotsPlugin,
UpdateSnapshotsPlugin.constructor,
{forbiddenOverwriteMessage: 'updating snapshots', key: 'u'},
],
[
UpdateSnapshotsInteractivePlugin,
UpdateSnapshotsInteractivePlugin.constructor,
{forbiddenOverwriteMessage: 'updating snapshots interactively', key: 'i'},
],
[QuitPlugin, {forbiddenOverwriteMessage: 'quitting watch mode'}],
[QuitPlugin.constructor, {forbiddenOverwriteMessage: 'quitting watch mode'}],
]);

export default function watch(
Expand Down Expand Up @@ -134,9 +147,10 @@ export default function watch(
});

if (globalConfig.watchPlugins != null) {
const watchPluginKeys = new Map();
const watchPluginKeys: WatchPluginKeysMap = new Map();
for (const plugin of watchPlugins) {
const reservedInfo = RESERVED_KEY_PLUGINS.get(plugin.constructor) || {};
const reservedInfo =
RESERVED_KEY_PLUGINS.get(plugin.constructor) || ({} as ReservedInfo);
const key = reservedInfo.key || getPluginKey(plugin, globalConfig);
if (!key) {
continue;
Expand Down Expand Up @@ -190,34 +204,38 @@ export default function watch(
emitFileChange();

hasteMapInstances.forEach((hasteMapInstance, index) => {
hasteMapInstance.on('change', ({eventsQueue, hasteFS, moduleMap}) => {
const validPaths = eventsQueue.filter(({filePath}) =>
isValidPath(globalConfig, filePath),
);

if (validPaths.length) {
const context = (contexts[index] = createContext(
contexts[index].config,
{hasteFS, moduleMap},
));

activePlugin = null;
hasteMapInstance.on(
'change',
({eventsQueue, hasteFS, moduleMap}: HasteChangeEvent) => {
const validPaths = eventsQueue.filter(({filePath}) =>
isValidPath(globalConfig, filePath),
);

searchSources = searchSources.slice();
searchSources[index] = {
context,
searchSource: new SearchSource(context),
};
emitFileChange();
startRun(globalConfig);
}
});
if (validPaths.length) {
const context = (contexts[index] = createContext(
contexts[index].config,
{hasteFS, moduleMap},
));

activePlugin = null;

searchSources = searchSources.slice();
searchSources[index] = {
context,
searchSource: new SearchSource(context),
};
emitFileChange();
startRun(globalConfig);
}
},
);
});

if (!hasExitListener) {
hasExitListener = true;
process.on('exit', () => {
if (activePlugin) {
// @ts-ignore: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33423
outputStream.write(ansiEscapes.cursorDown());
outputStream.write(ansiEscapes.eraseDown);
}
Expand Down Expand Up @@ -383,6 +401,7 @@ export default function watch(
break;
case 'w':
if (!shouldDisplayWatchUsage && !isWatchUsageDisplayed) {
// @ts-ignore: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/33423
outputStream.write(ansiEscapes.cursorUp());
outputStream.write(ansiEscapes.eraseDown);
outputStream.write(usage(globalConfig, watchPlugins));
Expand Down Expand Up @@ -413,7 +432,7 @@ export default function watch(
}

const checkForConflicts = (
watchPluginKeys,
watchPluginKeys: WatchPluginKeysMap,
plugin: WatchPlugin,
globalConfig: Config.GlobalConfig,
) => {
Expand Down
14 changes: 7 additions & 7 deletions packages/jest-haste-map/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import watchmanCrawl from './crawlers/watchman';
import WatchmanWatcher from './lib/WatchmanWatcher';
import * as fastPath from './lib/fast_path';
import {
ChangeEvent,
EventsQueue,
FileMetaData,
HasteMap as InternalHasteMapObject,
HasteRegExp,
Expand Down Expand Up @@ -104,6 +106,7 @@ namespace HasteMap {
export type SerializableModuleMap = HasteSerializableModuleMap;
export type FS = HasteFS;
export type HasteMapObject = InternalHasteMapObject;
export type HasteChangeEvent = ChangeEvent;
}

const CHANGE_INTERVAL = 30;
Expand Down Expand Up @@ -764,11 +767,7 @@ class HasteMap extends EventEmitter {
const rootDir = this._options.rootDir;

let changeQueue: Promise<null | void> = Promise.resolve();
let eventsQueue: Array<{
filePath: Config.Path;
stat: fs.Stats | undefined;
type: string;
}> = [];
let eventsQueue: EventsQueue = [];
// We only need to copy the entire haste map once on every "frame".
let mustCopy = true;

Expand Down Expand Up @@ -797,7 +796,7 @@ class HasteMap extends EventEmitter {
const emitChange = () => {
if (eventsQueue.length) {
mustCopy = true;
this.emit('change', {
const changeEvent: ChangeEvent = {
eventsQueue,
hasteFS: new HasteFS({
files: hasteMap.files,
Expand All @@ -809,7 +808,8 @@ class HasteMap extends EventEmitter {
mocks: hasteMap.mocks,
rootDir,
}),
});
};
this.emit('change', changeEvent);
eventsQueue = [];
}
};
Expand Down
Loading

0 comments on commit e48cd88

Please sign in to comment.