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

[2] Press "u" to update snapshots from watch mode #1479

Closed
wants to merge 3 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
20 changes: 15 additions & 5 deletions packages/jest-cli/src/cli/args.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ const check = (argv: Object) => {
);
}

if (argv.watchExtensions && argv.watch === undefined) {
if (argv.onlyChanged && argv.watchAll) {
throw new Error(
'--watchExtensions can only be specified together with --watch.',
'Both --onlyChanged and --watchAll were specified, but these two ' +
'options do not make sense together. Try the --watch option which ' +
'reruns only tests related to changed files.',
);
}

Expand Down Expand Up @@ -148,10 +150,18 @@ const options = {
watch: {
description: wrap(
'Watch files for changes and rerun tests related to changed files. ' +
'If you want to re-run all tests when a file has changed, you can ' +
'call Jest using `--watch=all`.',
'If you want to re-run all tests when a file has changed, use the ' +
'`--watchAll` option.',
),
type: 'string',
type: 'boolean',
},
watchAll: {
description: wrap(
'Watch files for changes and rerun all tests. If you want to re-run ' +
'only the tests related to the changed files, use the ' +
'`--watch` option.',
),
type: 'boolean',
},
bail: {
alias: 'b',
Expand Down
108 changes: 73 additions & 35 deletions packages/jest-cli/src/jest.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ const CLEAR = '\x1B[2J\x1B[H';
const VERSION = require('../package.json').version;
const WATCHER_DEBOUNCE = 200;
const WATCHMAN_BIN = 'watchman';
const KEYS = {
CONTROL_C: '03',
CONTROL_D: '04',
ENTER: '0d',
U: '75',
};

function getMaxWorkers(argv) {
if (argv.runInBand) {
Expand All @@ -51,7 +57,7 @@ function buildTestPathPatternInfo(argv) {
return {
lastCommit: argv.lastCommit,
onlyChanged: true,
watch: argv.watch !== undefined,
watch: argv.watch,
};
}
if (argv.testPathPattern) {
Expand Down Expand Up @@ -151,42 +157,74 @@ function runCLI(argv: Object, root: Path, onComplete: () => void) {
pipe.write('test framework = ' + testFramework.name + '\n');
pipe.write('config = ' + JSON.stringify(config, null, ' ') + '\n');
}
if (argv.watch !== undefined) {
if (argv.watch !== 'all') {
argv.onlyChanged = true;
}
if (argv.watch || argv.watchAll) {
argv.onlyChanged = !argv.watchAll;

let isRunning: ?boolean;
let timer: ?number;

const startRun = (overrideConfig: Object = {}) => {
if (isRunning) {
return;
}

pipe.write(CLEAR);
isRunning = true;
runJest(
Object.freeze(Object.assign({}, config, overrideConfig)),
argv,
pipe,
() => {
isRunning = false;
},
).then(
() => {},
error => console.error(chalk.red(error)),
);
};

const onKeypress = (key: string) => {
switch (key) {
case KEYS.CONTROL_C:
process.exit(0);
break;
case KEYS.CONTROL_D:
process.exit(0);
break;
case KEYS.ENTER:
startRun();
break;
case KEYS.U:
startRun({updateSnapshot: true});
break;
}
};

const onFileChange = (_, filePath: string) => {
filePath = path.join(root, filePath);
const isValidPath =
config.testPathDirs.some(dir => filePath.startsWith(dir));

return new Promise(resolve => {
getWatcher(config, root, watcher => {
let timer;
let isRunning;

pipe.write(CLEAR);
watcher.on('all', (_, filePath) => {
pipe.write(CLEAR);
filePath = path.join(root, filePath);
const isValidPath =
config.testPathDirs.some(dir => filePath.startsWith(dir));
if (!isRunning && isValidPath) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(
() => {
isRunning = true;
runJest(config, argv, pipe, () => isRunning = false)
.then(
resolve,
error => console.error(chalk.red(error)),
);
},
WATCHER_DEBOUNCE,
);
}
});
});
if (!isValidPath) {
return;
}
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(startRun, WATCHER_DEBOUNCE);
};

if (typeof process.stdin.setRawMode === 'function') {
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding('hex');
process.stdin.on('data', onKeypress);
}
getWatcher(config, root, watcher => {
Copy link
Member

Choose a reason for hiding this comment

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

remove the curly braces please :)

watcher.on('all', onFileChange);
});
startRun();
} else {
return runJest(config, argv, pipe, onComplete);
}
Expand Down
15 changes: 10 additions & 5 deletions packages/jest-cli/src/reporters/SummaryReporter.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class SummareReporter extends BaseReporter {
}

this._printSummary(aggregatedResults, config);
this._printSnapshotSummary(snapshots);
this._printSnapshotSummary(snapshots, config);
if (totalTestSuites) {
results +=
`${PASS_COLOR(`${pluralize('test', passedTests)} passed`)} (` +
Expand All @@ -73,18 +73,23 @@ class SummareReporter extends BaseReporter {
}
}

_printSnapshotSummary(snapshots: SnapshotSummary) {
_printSnapshotSummary(snapshots: SnapshotSummary, config: Config) {
if (
snapshots.added ||
snapshots.filesRemoved ||
snapshots.unchecked ||
snapshots.unmatched ||
snapshots.updated
) {
let updateCommand;
const event = process.env.npm_lifecycle_event;
const updateCommand =
(!event ? 're-' : '') + 'run with `' +
(event ? 'npm ' + event + ' -- ' : '') + '-u`';
if (config.watch) {
updateCommand = 'press "u"';
} else if (event) {
updateCommand = `run with \`npm ${event} -- -u\``;
} else {
updateCommand = 're-run with `-u`';
}

this.log('\n' + SNAPSHOT_SUMMARY('Snapshot Summary'));
if (snapshots.added) {
Expand Down
1 change: 1 addition & 0 deletions packages/jest-config/src/defaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ module.exports = ({
testURL: 'about:blank',
useStderr: false,
verbose: false,
watch: false,
}: DefaultConfig);
5 changes: 5 additions & 0 deletions packages/jest-config/src/setFromArgv.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ function setFromArgv(config, argv) {
if (argv.updateSnapshot) {
config.updateSnapshot = argv.updateSnapshot;
}

if (argv.watch || argv.watchAll) {
config.watch = true;
}

config.noStackTrace = argv.noStackTrace;

config.testcheckOptions = {
Expand Down
1 change: 1 addition & 0 deletions packages/jest-snapshot/src/SnapshotFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ class SnapshotFile {
this._content = Object.create(null);
if (this.fileExists(filename)) {
try {
delete require.cache[require.resolve(filename)];
Copy link
Member

Choose a reason for hiding this comment

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

<3 awesome.

/* eslint-disable no-useless-call */
Object.assign(this._content, require.call(null, filename));
/* eslint-enable no-useless-call */
Expand Down
1 change: 1 addition & 0 deletions types/Config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ type BaseConfig = {
testURL: string,
useStderr: boolean,
verbose: boolean,
watch: boolean,
};

export type DefaultConfig = BaseConfig & {
Expand Down