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

Interactive Snapshot Update mode #3831

Merged
merged 14 commits into from
Jan 11, 2018
Merged
Show file tree
Hide file tree
Changes from 4 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
138 changes: 138 additions & 0 deletions packages/jest-cli/src/SnapshotInteractiveMode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/**
Copy link
Member

Choose a reason for hiding this comment

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

This will need Facebook's copyright header. Can you copy it from other files?

* @flow
*/

import type {AggregatedResult} from 'types/TestResult';

const chalk = require('chalk');
const ansiEscapes = require('ansi-escapes');
const {pluralize} = require('./reporters/utils');
const {rightPad} = require('./lib/terminalUtils');
const {KEYS} = require('./constants');

module.exports = class SnapshotInteractiveMode {
_pipe: stream$Writable | tty$WriteStream;
_isActive: boolean;
_updateTestRunnerConfig: (a: string, jestRunnerOptions: Object) => *;
_testFilePaths: Array<string>;
_countPaths: number;

constructor(pipe: stream$Writable | tty$WriteStream) {
this._pipe = pipe;
this._isActive = false;
}

isActive() {
return this._isActive;
}

_drawUIOverlay() {
this._pipe.write(ansiEscapes.scrollDown);
this._pipe.write(ansiEscapes.scrollDown);

this._pipe.write(ansiEscapes.cursorSavePosition);
this._pipe.write(ansiEscapes.cursorTo(0, 0));

const title = rightPad(' -> Interactive Snapshot Update Activated <-');
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why rightPad? You can offset this from left by 4 spaces. Also I'd rename this to just:
Interactive Snapshot Update Mode

Copy link
Collaborator

Choose a reason for hiding this comment

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

Also, this text appears in "random" position.

screen shot 2017-06-29 at 13 32 10

Can we put it on top? Or even resign, as we have information about Interactive Snapshot Progress below.

this._pipe.write(chalk.black.bold.bgYellow(title));

this._pipe.write(ansiEscapes.cursorRestorePosition);
this._pipe.write(ansiEscapes.cursorUp(6));
this._pipe.write(ansiEscapes.eraseDown);

const numFailed = this._testFilePaths.length;
const numPass = this._countPaths - this._testFilePaths.length;

let stats = chalk.bold.red(pluralize('suite', numFailed) + ' failed');
if (numPass) {
stats += ', ' + chalk.bold.green(pluralize('suite', numPass) + ' passed');
}
const messages = [
'\n' + chalk.bold('Interactive Snapshot Progress'),
' \u203A ' + stats,
'\n' + chalk.bold('Watch Usage'),
Copy link
Collaborator

Choose a reason for hiding this comment

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

Change to Interactive Snapshot Mode Usage

chalk.dim(' \u203A Press ') +
'u' +
chalk.dim(' to update failing snapshots.'),
Copy link
Collaborator

Choose a reason for hiding this comment

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

I'd rather like something more descriptive:
Press u to update failing snapshots for this test.

this._testFilePaths.length > 1
? chalk.dim(' \u203A Press ') +
's' +
chalk.dim(' to skip the current snapshot..')
Copy link
Collaborator

@thymikee thymikee Jun 29, 2017

Choose a reason for hiding this comment

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

Remove the extra dot

: '',
chalk.dim(' \u203A Press ') +
'q' +
Copy link
Collaborator

Choose a reason for hiding this comment

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

Change to Esc, like we do in Pattern Mode

chalk.dim(' to quit interactive snapshot mode.'),
Copy link
Collaborator

@thymikee thymikee Jun 29, 2017

Choose a reason for hiding this comment

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

to quit Interactive Snapshot Update Mode

chalk.dim(' \u203A Press ') +
'Enter' +
chalk.dim(' to trigger a test run.'),
];

this._pipe.write(messages.filter(message => !!message).join('\n') + '\n');
}

put(key: string) {
switch (key) {
case KEYS.S:
const testFilePath = this._testFilePaths.shift();
this._testFilePaths.push(testFilePath);
this._run({});
break;

case KEYS.U:
this._run({updateSnapshot: 'all'});
break;

case KEYS.Q:
case KEYS.ESCAPE:
this.abort();
break;

Copy link
Collaborator

Choose a reason for hiding this comment

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

Can we remove these newlines?

case KEYS.ENTER:
this._run({});
break;
default:
console.log('got key event', key);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Remove this.

break;
}
}

abort() {
this._isActive = false;
this._updateTestRunnerConfig('', {});
}

updateWithResults(results: AggregatedResult) {
const hasSnapshotFailure = !!results.snapshot.failure;
if (hasSnapshotFailure) {
this._drawUIOverlay();
return;
}

this._testFilePaths.shift();
if (this._testFilePaths.length === 0) {
this.abort();
return;
}
this._run({});
}

_run(jestRunnerOptions: Object) {
const testFilePath = this._testFilePaths[0];
this._updateTestRunnerConfig(testFilePath, jestRunnerOptions);
}

run(
failedSnapshotTestPaths: Array<string>,
onConfigChange: (path: string, jestRunnerOptions: Object) => *,
) {
if (!failedSnapshotTestPaths.length) {
return;
}

this._testFilePaths = [].concat(failedSnapshotTestPaths);
this._countPaths = this._testFilePaths.length;
this._updateTestRunnerConfig = onConfigChange;
this._isActive = true;
this._run({});
}
};
138 changes: 138 additions & 0 deletions packages/jest-cli/src/__tests__/SnapshotInteractiveMode-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
const chalk = require('chalk');
import {KEYS} from '../constants';
import SnapshotInteractiveMode from '../SnapshotInteractiveMode';

jest.mock('../lib/terminalUtils', () => ({
getTerminalWidth: () => 80,
rightPad: () => {
'';
},
}));

jest.mock('ansi-escapes', () => ({
cursorRestorePosition: '[MOCK - cursorRestorePosition]',
cursorSavePosition: '[MOCK - cursorSavePosition]',
cursorScrollDown: '[MOCK - cursorScrollDown]',
cursorTo: (x, y) => `[MOCK - cursorTo(${x}, ${y})]`,
cursorUp: () => '[MOCK - cursorUp]',
eraseDown: '[MOCK - eraseDown]',
}));

jest.doMock('chalk', () =>
Object.assign(new chalk.constructor({enabled: false}), {
stripColor: str => str,
}),
);

describe('SnapshotInteractiveMode', () => {
let pipe;
let instance;

beforeEach(() => {
pipe = {write: jest.fn()};
instance = new SnapshotInteractiveMode(pipe);
});

test('is inactive at construction', () => {
expect(instance.isActive()).toBeFalsy();
});

test('call to run process the first file', () => {
const mockCallback = jest.fn();
instance.run(['first.js', 'second.js'], mockCallback);
expect(instance.isActive()).toBeTruthy();
expect(mockCallback).toBeCalledWith('first.js', {});
});

test('call to abort', () => {
const mockCallback = jest.fn();
instance.run(['first.js', 'second.js'], mockCallback);
expect(instance.isActive()).toBeTruthy();
instance.abort();
expect(instance.isActive()).toBeFalsy();
expect(mockCallback).toBeCalledWith('', {});
});
describe('key press handler', () => {
test('call to skip trigger a processing of next file', () => {
const mockCallback = jest.fn();
instance.run(['first.js', 'second.js'], mockCallback);
expect(mockCallback.mock.calls[0]).toEqual(['first.js', {}]);
instance.put(KEYS.S);
expect(mockCallback.mock.calls[1]).toEqual(['second.js', {}]);
instance.put(KEYS.S);
expect(mockCallback.mock.calls[2]).toEqual(['first.js', {}]);
});

test('call to skip works with 1 file', () => {
const mockCallback = jest.fn();
instance.run(['first.js'], mockCallback);
expect(mockCallback.mock.calls[0]).toEqual(['first.js', {}]);
instance.put(KEYS.S);
expect(mockCallback.mock.calls[1]).toEqual(['first.js', {}]);
});

test('press U trigger a snapshot update call', () => {
const mockCallback = jest.fn();
instance.run(['first.js'], mockCallback);
expect(mockCallback.mock.calls[0]).toEqual(['first.js', {}]);
instance.put(KEYS.U);
expect(mockCallback.mock.calls[1]).toEqual([
'first.js',
{updateSnapshot: 'all'},
]);
});

test('press Q or ESC triggers an abort', () => {
instance.abort = jest.fn();
instance.put(KEYS.Q);
instance.put(KEYS.ESCAPE);
expect(instance.abort).toHaveBeenCalledTimes(2);
});

test('press ENTER trigger a run', () => {
const mockCallback = jest.fn();
instance.run(['first.js'], mockCallback);
instance.put(KEYS.ENTER);
expect(mockCallback).toHaveBeenCalledTimes(2);
expect(mockCallback).toHaveBeenCalledWith('first.js', {});
});
});
describe('updateWithResults', () => {
test('with a test failure simply update UI', () => {
const mockCallback = jest.fn();
instance.run(['first.js'], mockCallback);
pipe.write('TEST RESULTS CONTENTS');
instance.updateWithResults({snapshot: {failure: true}});
expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot();
expect(mockCallback).toHaveBeenCalledTimes(1);
});

test('with a test success, call the next test', () => {
const mockCallback = jest.fn();
instance.run(['first.js', 'second.js'], mockCallback);
pipe.write('TEST RESULTS CONTENTS');
instance.updateWithResults({snapshot: {failure: false}});
expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot();
expect(mockCallback.mock.calls[1]).toEqual(['second.js', {}]);
});

test('overlay handle progress UI', () => {
const mockCallback = jest.fn();
instance.run(['first.js', 'second.js', 'third.js'], mockCallback);
pipe.write('TEST RESULTS CONTENTS');
instance.updateWithResults({snapshot: {failure: false}});
instance.updateWithResults({snapshot: {failure: true}});
expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot();
});

test('last test success, trigger end of interactive mode', () => {
const mockCallback = jest.fn();
instance.abort = jest.fn();
instance.run(['first.js'], mockCallback);
pipe.write('TEST RESULTS CONTENTS');
instance.updateWithResults({snapshot: {failure: false}});
expect(pipe.write.mock.calls.join('\n')).toMatchSnapshot();
expect(instance.abort).toHaveBeenCalled();
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`SnapshotInteractiveMode updateWithResults last test success, trigger end of interactive mode 1`] = `"TEST RESULTS CONTENTS"`;

exports[`SnapshotInteractiveMode updateWithResults overlay handle progress UI 1`] = `
"TEST RESULTS CONTENTS


[MOCK - cursorSavePosition]
[MOCK - cursorTo(0, 0)]
<bold>undefined</>
[MOCK - cursorRestorePosition]
[MOCK - cursorUp]
[MOCK - eraseDown]

<bold>Interactive Snapshot Progress
› <bold><red>2 suites failed</>, <bold><green>1 suite passed</>

<bold>Watch Usage
<dim> › Press u<dim> to update failing snapshots.
<dim> › Press s<dim> to skip the current snapshot..
<dim> › Press q<dim> to quit interactive snapshot mode.
<dim> › Press Enter<dim> to trigger a test run.
"
`;

exports[`SnapshotInteractiveMode updateWithResults with a test failure simply update UI 1`] = `
"TEST RESULTS CONTENTS


[MOCK - cursorSavePosition]
[MOCK - cursorTo(0, 0)]
<bold>undefined</>
[MOCK - cursorRestorePosition]
[MOCK - cursorUp]
[MOCK - eraseDown]

<bold>Interactive Snapshot Progress
› <bold><red>1 suite failed</>

<bold>Watch Usage
<dim> › Press u<dim> to update failing snapshots.
<dim> › Press q<dim> to quit interactive snapshot mode.
<dim> › Press Enter<dim> to trigger a test run.
"
`;

exports[`SnapshotInteractiveMode updateWithResults with a test success, call the next test 1`] = `"TEST RESULTS CONTENTS"`;
2 changes: 2 additions & 0 deletions packages/jest-cli/src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ const KEYS = {
CONTROL_D: '04',
ENTER: '0d',
ESCAPE: '1b',
I: '69',
O: '6f',
P: '70',
Q: '71',
QUESTION_MARK: '3f',
S: '73',
T: '74',
U: '75',
W: '77',
Expand Down
9 changes: 8 additions & 1 deletion packages/jest-cli/src/lib/terminalUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,15 @@
*/

/* $FlowFixMe */
const getTerminalWidth = (): nubmer => process.stdout.columns;
const getTerminalWidth = (): number => process.stdout.columns;

const rightPad = (input: string): string => {
const termWidth = getTerminalWidth();
input += Array(termWidth - input.length + 1).join(' ');
return input;
};

module.exports = {
getTerminalWidth,
rightPad,
};
Loading