Skip to content

Commit

Permalink
Snapshot menu (jest-community#949)
Browse files Browse the repository at this point in the history
* add snapshot-provider

* added snapshot profile, menu and commands

* remove listener update-snapshot request

* refactor TestResultProvider and removed enableSnapshotUpdateMessages

* removed SnapshotCodeLenses

* fix publish parsed source file to test explorer

* fixes broken tests

* clean up console output messages

* upgrade jest-editor-support

* adding tests for changes

* use context menu for all snapshot operations

* adding tests for changes

* handle multiple snapshots in a given test

* rename testResolveProvider to testResultProvider

* upgrade jest-editor-support

* address lint error/warning
  • Loading branch information
connectdotz committed Nov 20, 2022
1 parent a4258e9 commit 1b47ec7
Show file tree
Hide file tree
Showing 41 changed files with 1,305 additions and 765 deletions.
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ Content
- [How to trigger the test run?](#how-to-trigger-the-test-run)
- [How to debug tests?](#how-to-debug-tests)
- [How to use code coverage?](#how-to-use-code-coverage)
- [How to update and view snpashots?](#how-to-update-and-view-snpashots)
- [How to use the extension with monorepo projects?](#how-to-use-the-extension-with-monorepo-projects)
- [How to read the StatusBar?](#how-to-read-the-statusbar)
- [How to use the Test Explorer?](#how-to-use-the-test-explorer)
Expand Down Expand Up @@ -83,7 +84,7 @@ Content
* Show fails inside the problem inspector.
* Highlights the errors next to the `expect` functions.
* Adds syntax highlighting to snapshot files.
* A one button update for failed snapshots.
* Update and view snapshots at any level.
* Show coverage information in files being tested.
* Help debug jest tests in vscode.
* Supports multiple test run modes (automated, manual, and hybrid onSave) to meet user's preferred development experience.
Expand Down Expand Up @@ -170,6 +171,8 @@ You can customize coverage start up behavior, style and colors, see [customizati

</details>

### How to update and view snpashots?

### How to use the extension with monorepo projects?

The easiest way to setup the monorepo projects is to use the [Setup Tool](setup-wizard.md#setup-monorepo-project) and choose **Setup monorepo project**
Expand Down Expand Up @@ -257,10 +260,6 @@ Users can use the following settings to tailor the extension for their environme
|**Editor**|
|<strike>enableInlineErrorMessages</strike> :x:| Whether errors should be reported inline on a file|--|This is now deprecated in favor of `jest.testExplorer` |
|[testExplorer](#testexplorer) |Configure jest test explorer|null|`{"showInlineError": "true"}`|
|**Snapshot**|
|enableSnapshotUpdateMessages|Whether snapshot update messages should show|true|`"jest.enableSnapshotUpdateMessages": false`|
|enableSnapshotPreviews 💼|Whether snapshot previews should show|true|`"jest.enableSnapshotPreviews": false`|
|restartJestOnSnapshotUpdate :x:| Restart Jest runner after updating the snapshots|false|This is no longer needed in v4|
|**Coverage**|
|showCoverageOnLoad|Show code coverage when extension starts|false|`"jest.showCoverageOnLoad": true`|
|[coverageFormatter](#coverageFormatter)|Determine the coverage overlay style|"DefaultFormatter"|`"jest.coverageFormatter": "GutterFormatter"`|
Expand Down
6 changes: 6 additions & 0 deletions __mocks__/vscode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const window = {
showWorkspaceFolderPick: jest.fn(),
onDidChangeActiveTextEditor: jest.fn(),
showInformationMessage: jest.fn(),
createWebviewPanel: jest.fn(),
};

const workspace = {
Expand Down Expand Up @@ -79,6 +80,10 @@ const TestRunProfileKind = {
Debug: 2,
Coverage: 3,
};
const ViewColumn = {
One: 1,
Tow: 2,
};

const TestMessage = jest.fn();
const TestRunRequest = jest.fn();
Expand Down Expand Up @@ -112,4 +117,5 @@ export = {
EventEmitter,
TestMessage,
TestRunRequest,
ViewColumn,
};
25 changes: 24 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,16 @@
"command": "io.orta.jest.test-item.coverage.toggle-on",
"title": "Toggle Coverage On",
"icon": "$(color-mode)"
},
{
"command": "io.orta.jest.test-item.view-snapshot",
"title": "View Snapshot",
"icon": "$(camera)"
},
{
"command": "io.orta.jest.test-item.update-snapshot",
"title": "Update Snapshot",
"icon": "$(export)"
}
],
"menus": {
Expand Down Expand Up @@ -363,6 +373,19 @@
"command": "io.orta.jest.test-item.coverage.toggle-on",
"group": "inline",
"when": "testId in jest.coverage.off"
},
{
"command": "io.orta.jest.test-item.update-snapshot"
}
],
"testing/item/gutter": [
{
"command": "io.orta.jest.test-item.view-snapshot",
"when": "testId in jest.editor-view-snapshot"
},
{
"command": "io.orta.jest.test-item.update-snapshot",
"when": "testId in jest.editor-update-snapshot"
}
]
},
Expand Down Expand Up @@ -501,7 +524,7 @@
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"istanbul-lib-source-maps": "^4.0.0",
"jest-editor-support": "^30.2.1"
"jest-editor-support": "^30.3.1"
},
"devDependencies": {
"@types/istanbul-lib-coverage": "^2.0.2",
Expand Down
4 changes: 4 additions & 0 deletions release-notes/release-note-v5.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ Users with jest coverageProvider `v8` should be able to see coverage like with t
- can not be turned off any more.
- removed the "enable" and "showClassicStatus" attributes. The only valid attribute is "showInlineError".
- `"jest.autoRun` default value has changed. see detail above.
- Snapshot changes:
- Snapshot codeLenses are gone and replaced with commands in test status and test explorer tree menu.
- No more snapshot update messaging when running tests but users can update any snapshot any time they want.
- Retired the following snapshot related settings: `jest.enableSnapshotPreviews`, `jest.enableSnapshotUpdateMessages`, `restartJestOnSnapshotUpdate`.
### Change log
- [v5.0.2 pre-release](https://github.com/jest-community/vscode-jest/releases/tag/v5.0.2)
- [v5.0.1 pre-release](https://github.com/jest-community/vscode-jest/releases/tag/v5.0.1)
Expand Down
7 changes: 5 additions & 2 deletions src/JestExt/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { extensionName, SupportedLanguageIds } from '../appGlobals';
import { createJestExtContext, getExtensionResourceSettings, prefixWorkspace } from './helper';
import { PluginResourceSettings } from '../Settings';
import { WizardTaskId } from '../setup-wizard';
import { JestExtExplorerContext } from '../test-provider/types';
import { ItemCommand, JestExtExplorerContext } from '../test-provider/types';
import { JestTestProvider } from '../test-provider';
import { JestProcessInfo } from '../JestProcessManagement';
import { addFolderToDisabledWorkspaceFolders } from '../extensionManager';
Expand Down Expand Up @@ -124,7 +124,7 @@ export class JestExt {
...this.extContext,
sessionEvents: this.events,
session: this.processSession,
testResolveProvider: this.testResultProvider,
testResultProvider: this.testResultProvider,
debugTests: this.debugTests,
};
}
Expand Down Expand Up @@ -631,6 +631,9 @@ export class JestExt {
// restart jest since coverage condition has changed
this.triggerUpdateSettings(this.extContext.settings);
}
runItemCommand(testItem: vscode.TestItem, itemCommand: ItemCommand): void {
this.testProvider?.runItemCommand(testItem, itemCommand);
}
enableLoginShell(): void {
if (this.extContext.settings.shell.useLoginShell) {
return;
Expand Down
1 change: 0 additions & 1 deletion src/JestExt/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ export const getExtensionResourceSettings = (uri: vscode.Uri): PluginResourceSet

return {
autoEnable,
enableSnapshotUpdateMessages: config.get<boolean>('enableSnapshotUpdateMessages'),
pathToConfig: config.get<string>('pathToConfig'),
jestCommandLine: config.get<string>('jestCommandLine'),
pathToJest: config.get<string>('pathToJest'),
Expand Down
45 changes: 0 additions & 45 deletions src/JestExt/process-listeners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,6 @@ export class ListTestFileListener extends AbstractProcessListener {
}
}

const SnapshotFailRegex = /(snapshots? failed)|(snapshot test failed)/i;
const IS_OUTSIDE_REPOSITORY_REGEXP =
/Test suite failed to run[\s\S]*fatal:[\s\S]*is outside repository/im;
const WATCH_IS_NOT_SUPPORTED_REGEXP =
Expand Down Expand Up @@ -264,54 +263,12 @@ export class RunTestListener extends AbstractProcessListener {
}
//=== private methods ===
private shouldIgnoreOutput(text: string): boolean {
// this fails when snapshots change - to be revised - returning always false for now
return text.length <= 0 || text.includes('Watch Usage');
}
private cleanupOutput(text: string): string {
return text.replace(CONTROL_MESSAGES, '');
}

// if snapshot error, offer update snapshot option and execute if user confirms
private handleSnapshotTestFailuer(process: JestProcess, data: string) {
// if already in the updateSnapshot run, do not prompt again
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((process.request as any).updateSnapshot) {
return;
}

if (
this.session.context.settings.enableSnapshotUpdateMessages &&
SnapshotFailRegex.test(data)
) {
const msg =
process.request.type === 'watch-all-tests' || process.request.type === 'watch-tests'
? 'all files'
: 'files in this run';
vscode.window
.showInformationMessage(
`[${this.session.context.workspace.name}] Would you like to update snapshots for ${msg}?`,
{
title: 'Replace them',
}
)
.then((response) => {
// No response == cancel
if (response) {
this.session.scheduleProcess({
type: 'update-snapshot',
baseRequest: process.request,
});
this.onRunEvent.fire({
type: 'data',
process,
text: 'Updating snapshots...',
newLine: true,
});
}
});
}
}

// restart the process with watch-all if it is due to "watch not supported" error
private handleWatchNotSupportedError(process: JestProcess, data: string) {
if (IS_OUTSIDE_REPOSITORY_REGEXP.test(data) || WATCH_IS_NOT_SUPPORTED_REGEXP.test(data)) {
Expand Down Expand Up @@ -359,8 +316,6 @@ export class RunTestListener extends AbstractProcessListener {

this.handleRunComplete(process, message);

this.handleSnapshotTestFailuer(process, message);

this.handleWatchNotSupportedError(process, message);
}

Expand Down
55 changes: 5 additions & 50 deletions src/JestExt/process-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,23 @@ import {
JestProcessRequestBase,
ScheduleStrategy,
requestString,
QueueType,
JestProcessInfo,
JestProcessRequestTransform,
} from '../JestProcessManagement';
import { JestTestProcessType } from '../Settings';
import { RunTestListener, ListTestFileListener } from './process-listeners';
import { JestExtProcessContext } from './types';

type InternalProcessType = 'list-test-files' | 'update-snapshot';
type InternalProcessType = 'list-test-files';
export type ListTestFilesCallback = (
fileNames?: string[],
error?: string,
exitCode?: number
) => void;
export type InternalRequestBase =
| {
type: Extract<InternalProcessType, 'list-test-files'>;
onResult: ListTestFilesCallback;
}
| {
type: Extract<InternalProcessType, 'update-snapshot'>;
baseRequest: JestProcessRequest;
};
export type InternalRequestBase = {
type: Extract<InternalProcessType, 'list-test-files'>;
onResult: ListTestFilesCallback;
};

export type JestExtRequestType = JestProcessRequestBase | InternalRequestBase;
const isJestProcessRequestBase = (request: JestExtRequestType): request is JestProcessRequestBase =>
Expand Down Expand Up @@ -122,32 +116,6 @@ export const createProcessSession = (context: JestExtProcessContext): ProcessSes
};
const listenerSession: ListenerSession = { context, scheduleProcess };

/**
* returns an update-snapshot process-request base on the current process
* @param process
* @returns undefined if the process already is updating snapshot
*/
const createSnapshotRequest = (baseRequest: JestProcessRequest): JestProcessRequestBase => {
switch (baseRequest.type) {
case 'watch-tests':
case 'watch-all-tests':
return { type: 'all-tests', updateSnapshot: true };
case 'all-tests':
case 'by-file':
case 'by-file-pattern':
case 'by-file-test':
case 'by-file-test-pattern':
if (baseRequest.updateSnapshot) {
throw new Error(
'schedule a update-snapshot run within an update-snapshot run is not supported'
);
}
return { ...baseRequest, updateSnapshot: true };
default:
throw new Error(`unexpeted baseRequest type for snapshot run: ${baseRequest.toString()}`);
}
};

const createProcessRequest = (request: JestExtRequestType): JestProcessRequest => {
const transform = (pRequest: JestProcessRequest): JestProcessRequest => {
const t = getTransform(request);
Expand All @@ -170,19 +138,6 @@ export const createProcessSession = (context: JestExtProcessContext): ProcessSes
schedule,
});
}
case 'update-snapshot': {
const snapshotRequest = createSnapshotRequest(request.baseRequest);
const schedule = {
...ProcessScheduleStrategy[snapshotRequest.type],
queue: 'non-blocking' as QueueType,
};

return transform({
...snapshotRequest,
listener: new RunTestListener(lSession),
schedule,
});
}
case 'list-test-files': {
const schedule = ProcessScheduleStrategy['not-test'];
return transform({
Expand Down
2 changes: 0 additions & 2 deletions src/JestProcessManagement/JestProcessManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ export class JestProcessManager implements TaskArrayFunctions<JestProcess> {
const process = task.data;

try {
this.logging('debug', 'starting process:', process);
await process.start();
this.logging('debug', 'process ended:', process);
} catch (e) {
this.logging('error', `${queue.name}: process failed:`, process, e);
} finally {
Expand Down
1 change: 0 additions & 1 deletion src/Settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export type NodeEnv = ProjectWorkspace['nodeEnv'];
export type MonitorLongRun = 'off' | number;
export interface PluginResourceSettings {
autoEnable?: boolean;
enableSnapshotUpdateMessages?: boolean;
jestCommandLine?: string;
pathToConfig?: string;
pathToJest?: string;
Expand Down
49 changes: 0 additions & 49 deletions src/SnapshotCodeLens/SnapshotCodeLensProvider.ts

This file was deleted.

0 comments on commit 1b47ec7

Please sign in to comment.