feat(run): watch mode for Jest and Vitest test runs (#6102) (#6102)

Jest and Vitest test run configurations get a watch option. A watched run keeps the runner alive, re-runs on file changes and ends each cycle in the test tree like a finished run; derived runs (rerun failed, run at cursor) run once.

Merged main in and combined the RunExtras watch field with the executor field that landed on main.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-27 00:42:53 +08:00
1 джерело da3b621345
коміт 144cd90175
24 files changed
+533 -14

No files matched your search

+4
Переглянути файл
@@ -120,6 +120,8 @@ struct FileConfig {
target: Option<String>,
#[serde(alias = "testRunner")]
test_runner: Option<String>,
#[serde(default)]
watch: bool,
}
pub(crate) fn slug(s: &str) -> String {
@@ -186,6 +188,7 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
stop_command: non_empty(c.stop_command),
target: non_empty(c.target),
test_runner: non_empty(c.test_runner),
watch: c.watch,
executor: None,
},
});
@@ -288,6 +291,7 @@ fn to_table(c: &RunConfig) -> Table {
("show-on-stderr", x.show_on_stderr),
("focus-tool-window", x.focus_tool_window),
("emulate-terminal", x.emulate_terminal),
("watch", x.watch),
] {
if on {
t.insert(key, value(true));
+5
Переглянути файл
@@ -188,6 +188,10 @@ pub struct RunExtras {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub test_runner: Option<String>,
/// Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub watch: bool,
/// The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set
/// on the launched copy, not saved; the plugin's executor-bound Java agent loads only then.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -217,6 +221,7 @@ impl Default for RunExtras {
stop_command: None,
target: None,
test_runner: None,
watch: false,
executor: None,
}
}
+1
Переглянути файл
@@ -134,6 +134,7 @@ fn extras_round_trip_and_local_file() {
shared.extras.open_tool_window = Some(false);
shared.extras.focus_tool_window = true;
shared.extras.emulate_terminal = true;
shared.extras.watch = true;
shared.extras.stop_command = Some("docker stop server".into());
let mut local = sample().remove(1);
local.extras.local = true;
+4
Переглянути файл
@@ -70,6 +70,10 @@ Detected test configurations show results in the tree automatically. For your ow
**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks.
### Watch mode (Jest, Vitest)
Turn on **Modify options › Watch for changes** in a Jest or Vitest test configuration, or the **Rerun Automatically** toggle in the test tree toolbar, to keep the runner watching (`jest --watchAll`, `vitest watch`). After each edit the tests run again in the same tab, and each cycle's results replace the previous ones in the tree. **Stop**, turning the toggle off, or closing the tab ends the watcher. Debug, **Rerun Failed Tests** and runs of selected tests run once. A script that runs `vitest run` is started as `vitest watch` through the package manager; a script that runs more than Jest or Vitest (`jest && eslint .`, `tsc && vitest run`) runs once.
## Navigate between code and tests
**Navigate › Test** (`⌘⇧T` / `Ctrl+Shift+T`) jumps from a class to its tests and back, using common naming conventions (`FooTest`, `test_foo.py`, `foo.test.ts`…) and the project's source and test roots. With several matches it shows a chooser. With none, **Create New Test…** creates one from the file templates.
+4
Переглянути файл
@@ -66,6 +66,10 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配
**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。
### 监视模式(Jest、Vitest)
在 Jest 或 Vitest 测试配置中打开 **修改选项 › 监视更改**,或在测试树工具栏打开 **自动重新运行**,测试运行器会持续监视文件(`jest --watchAll`、`vitest watch`)。每次编辑后测试会在同一个标签页中重新运行,每一轮的结果替换树中上一轮的结果。点击 **停止**、关闭这个开关或关闭标签页都会结束监视进程。调试、**重新运行失败的测试**和运行选中的测试都只运行一次。运行 `vitest run` 的脚本会通过包管理器以 `vitest watch` 启动;除了 Jest 或 Vitest 还运行其他命令的脚本(`jest && eslint .`、`tsc && vitest run`)只运行一次。
## 在代码和测试之间跳转
**导航 › 测试**(`⌘⇧T` / `Ctrl+Shift+T`)会根据常见命名约定(`FooTest`、`test_foo.py`、`foo.test.ts` 等)和项目的源码 / 测试根目录,在类和它的测试之间来回跳转。匹配到多个时弹出选择列表;一个都没有时,可以用 **创建新测试…** 从文件模板新建。
+4
Переглянути файл
@@ -12552,6 +12552,8 @@ export type RunExtras_Deserialize = {
* test output parser and how a single test is selected.
*/
testRunner?: string | null,
/** Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit. */
watch?: boolean,
/**
* The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set
* on the launched copy, not saved; the plugin's executor-bound Java agent loads only then.
@@ -12607,6 +12609,8 @@ export type RunExtras_Serialize = {
* test output parser and how a single test is selected.
*/
testRunner?: string | null,
/** Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit. */
watch?: boolean,
/**
* The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set
* on the launched copy, not saved; the plugin's executor-bound Java agent loads only then.
+18 -2
Переглянути файл
@@ -61,6 +61,7 @@ import { PluginArgsInput } from "./PluginArgsInput";
import { pluginOwnedConfig } from "./pluginArgsCompletion";
import { useBuildModel } from "@/platform/buildModel";
import { COMPOUND, formParams, terminalApplies, withParams } from "./types";
import { frameworkFor } from "./testing";
import { TomcatSettings } from "./TomcatSettings";
import { toolWindowTitle } from "@/workbench/toolwindows/title";
import styles from "./Run.module.css";
@@ -109,6 +110,7 @@ export type OptionId =
| "openToolWindow"
| "focusToolWindow"
| "isTest"
| "watch"
| "emulateTerminal";
const VALUE_OPTIONS: ReadonlySet<OptionId> = new Set([
@@ -131,13 +133,14 @@ const OPTION_LABELS: Record<OptionId, string> = {
openToolWindow: "Open run/debug tool window when started",
focusToolWindow: "Focus run/debug tool window when started",
isTest: "Show results in the test runner",
watch: "Watch for changes",
emulateTerminal: "Emulate terminal in output console",
};
const OPTION_GROUPS: ReadonlyArray<{ label: string; options: OptionId[]; process: boolean }> = [
{ label: "Operating System", options: ["allowParallel", "stdinFile", "envFiles", "emulateTerminal"], process: true },
{ label: "Logs", options: ["outputFile", "showOnStdout", "showOnStderr"], process: true },
{ label: "Test", options: ["isTest"], process: true },
{ label: "Test", options: ["isTest", "watch"], process: true },
{
label: "Before Launch",
options: ["buildPolicy", "beforeLaunch", "openToolWindow", "focusToolWindow"],
@@ -170,6 +173,8 @@ export function optionSet(config: RunConfig, id: OptionId, openByDefault: boolea
return !!config.focusToolWindow;
case "isTest":
return config.isTest;
case "watch":
return !!config.watch;
case "emulateTerminal":
return !!config.emulateTerminal;
}
@@ -200,6 +205,8 @@ export function optionPatch(id: OptionId, on: boolean): Partial<RunConfig> {
return { focusToolWindow: on };
case "isTest":
return on ? { isTest: true, emulateTerminal: false } : { isTest: false };
case "watch":
return { watch: on };
case "emulateTerminal":
return { emulateTerminal: on };
}
@@ -398,6 +405,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
};
const terminal = terminalApplies(config, type);
const watchApplies = config.isTest && frameworkFor(config) === "js";
// A terminal has no separate input file: the two options exclude each other.
const blocked = (id: OptionId) =>
(id === "emulateTerminal" && isShown("stdinFile")) || (id === "stdinFile" && !!config.emulateTerminal);
@@ -408,7 +416,8 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
(id) =>
(!compound || id === "beforeLaunch") &&
(id !== "emulateTerminal" || terminal || !!config.emulateTerminal) &&
(id !== "buildPolicy" || buildPolicyApplies(config)),
(id !== "buildPolicy" || buildPolicyApplies(config)) &&
(id !== "watch" || watchApplies),
)
.map((id): MenuItem => ({
label: OPTION_LABELS[id],
@@ -498,6 +507,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
"openToolWindow",
"focusToolWindow",
"isTest",
"watch",
] as const
).filter(
(id) => (!noProcess || id === "openToolWindow" || id === "focusToolWindow") && optionSet(config, id, openByDefault),
@@ -911,6 +921,12 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
</div>
)}
{config.watch && watchApplies && !noProcess && (
<div className={styles.notice}>
<T>Debug runs the tests once, without watching.</T>
</div>
)}
{!noProcess && !template && (
<div className={styles.editPreview}>
<span className={styles.chooserMuted}>
+11 -1
Переглянути файл
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { debugSession, resetRuns, useRun, type RunSession } from "./store";
import { sessionIcon } from "./RunView";
import { sessionIcon, testsRun } from "./RunView";
const actions = vi.hoisted(() => ({ executeAction: vi.fn() }));
vi.mock("@/platform/actions", async (orig) => ({ ...(await orig<object>()), executeAction: actions.executeAction }));
@@ -80,3 +80,13 @@ describe("debugSession", () => {
expect(actions.executeAction).not.toHaveBeenCalled();
});
});
describe("testsRun", () => {
const live = { status: "running" } as RunSession;
it("ends a watch run's tests with each cycle", () => {
expect(testsRun({ ...live, watching: true }, { finished: false })).toBe("running");
expect(testsRun({ ...live, watching: true }, { finished: true })).toBe("done");
expect(testsRun(live, { finished: true })).toBe("running");
expect(testsRun({ ...live, status: "finished" }, { finished: false })).toBe("done");
});
});
+18 -3
Переглянути файл
@@ -38,6 +38,7 @@ import {
rerunSession,
resizeTerminal,
runSelectedTests,
toggleRerunAutomatically,
runtime,
sendStdin,
setPendingInput,
@@ -50,7 +51,7 @@ import {
pinSession,
} from "./store";
import { rerunFailedConfigs } from "./testing/rerun";
import { formatDuration, nodeOutput } from "./testing";
import { formatDuration, frameworkFor, nodeOutput } from "./testing";
import { TestStatusBar, TestTreeView } from "./TestTreeView";
import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace";
import { ThreadDumpPanel } from "./threadDump/ThreadDumpPanel";
@@ -143,6 +144,7 @@ export function SessionPanel({
if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]);
}, [hasTests, testOrientation]);
const running = isLive(session);
const testsRunning = testsRun(session, rt?.tests) === "running";
const cwd = runDirectory(session.config.cwd);
const baseConfig = useRun(() => baseConfigOf(session));
// Test results mutate in place; their version refreshes the selection.
@@ -211,7 +213,7 @@ export function SessionPanel({
const consoleColumn = (
<div className={styles.consoleColumn}>
{rt.tests && <TestStatusBar results={rt.tests} version={version} running={running} />}
{rt.tests && <TestStatusBar results={rt.tests} version={version} running={testsRunning} />}
{rt.console.dropped > 0 && !testModel && (
<div className={styles.notice}>{tx`${rt.console.dropped.toLocaleString()} earlier lines were discarded`}</div>
)}
@@ -411,7 +413,7 @@ export function SessionPanel({
results={rt.tests}
version={version}
cwd={cwd}
running={running}
running={testsRunning}
name={session.config.name}
selected={selectedTest}
onSelect={setSelectedTest}
@@ -419,6 +421,11 @@ export function SessionPanel({
onUpdateSnapshots={(ids) => void updateSnapshots(session.id, ids)}
canRunTests={(ids) => canRunSelectedTests(session.id, ids)}
onRunTests={(ids, debug) => void runSelectedTests(session.id, ids, debug)}
rerunAutomatically={
frameworkFor(session.config) === "js"
? { on: !!session.watching && running, toggle: () => toggleRerunAutomatically(session.id) }
: undefined
}
/>
</SplitPanel>
<SplitHandle />
@@ -434,6 +441,14 @@ export function SessionPanel({
);
}
/**
* Whether a session's tests still run: a watch run's are done at the end of each cycle, like a
* finished run (status, Sort by Duration, Select First Failed).
*/
export function testsRun(session: RunSession, tests: { finished: boolean } | null | undefined): "running" | "done" {
return isLive(session) && !(session.watching && tests?.finished) ? "running" : "done";
}
function sessionItems(sessions: readonly RunSession[], targets: readonly RunTargetValid[]): TabItem[] {
return sessions.map((s) => {
const label = remoteLabel(s.config, targets);
+22
Переглянути файл
@@ -168,6 +168,28 @@ describe("TestTreeView", () => {
);
});
it("shows Rerun Automatically only where watch mode applies", () => {
const { unmount } = render(<Host />);
expect(screen.queryByRole("button", { name: "Rerun Automatically" })).toBeNull();
unmount();
const toggle = vi.fn();
render(
<TestTreeView
results={results()}
version={1}
cwd="/p"
selected={null}
onSelect={() => {}}
running
rerunAutomatically={{ on: true, toggle }}
/>,
);
const button = screen.getByRole("button", { name: "Rerun Automatically" });
expect(button.getAttribute("aria-pressed")).toBe("true");
fireEvent.click(button);
expect(toggle).toHaveBeenCalledOnce();
});
describe("Previous / Next Failed Test", () => {
const navigate = vi.fn();
beforeEach(() => {
+13
Переглянути файл
@@ -194,6 +194,8 @@ export interface TestTreeViewProps {
/** Run / Debug the selected tests (context menu); absent when the configuration can't be narrowed. */
onRunTests?: (ids: string[], debug: boolean) => void;
canRunTests?: (ids: string[]) => boolean | Promise<boolean>;
/** Jest / Vitest runs: the "Rerun Automatically" (watch mode) toggle. */
rerunAutomatically?: { on: boolean; toggle: () => void };
}
export function TestTreeView({
@@ -208,6 +210,7 @@ export function TestTreeView({
canUpdateSnapshots,
onRunTests,
canRunTests,
rerunAutomatically,
}: TestTreeViewProps) {
const [filters, setFilters] = useState(loadTestFilters);
const { showPassed, showIgnored, showDurations, selectFirstFailed, sortAlphabetically, sortByDuration } = filters;
@@ -385,6 +388,16 @@ export function TestTreeView({
return (
<div className={styles.testPane}>
<Toolbar className={styles.testToolbar} aria-label="Test results">
{rerunAutomatically && (
<IconButton
icon="rerun-automatically"
size="small"
iconSize={16}
title="Rerun Automatically"
pressed={rerunAutomatically.on}
onClick={rerunAutomatically.toggle}
/>
)}
<div className={styles.testFilters}>
<IconButton
icon="test-show-passed"
+33 -2
Переглянути файл
@@ -57,6 +57,7 @@ import { TeamcityOutput } from "./testing/teamcity";
import type { TestStdout } from "./testing/types";
import { flutterMachineOutput, isFlutterMachineRun } from "./flutterMachine";
import { recordTestStates } from "./testing/states";
import { packageScript, watchLaunch } from "./testing/watch";
import { failedTestPaths, leafTestPaths, rerunFailedConfigs, testsConfigs } from "./testing/rerun";
import { testsBySubproject } from "./testing/gradleSubprojects";
import {
@@ -113,6 +114,8 @@ export interface RunSession {
pinned?: boolean;
/** Commit checks own these tabs so their output stays available for review. */
backgroundCheck?: boolean;
/** Jest / Vitest watch mode: the process reruns the tests after each edit. */
watching?: boolean;
}
interface SessionRuntime {
@@ -792,8 +795,13 @@ function newRuntime(config: RunConfig): SessionRuntime {
})
: null;
const parser = pluginTests ? null : builtIn;
// A watch cycle's end records the test states like a finished run (gutter icons).
const applyTests = (events: TestEvent[]) => {
tests!.apply(events);
if (events.some((e) => e.type === "end")) recordTestStates(tests!);
};
const feed = (line: string) => {
if (tests && parser) tests.apply(parser.feed(line));
if (tests && parser) applyTests(parser.feed(line));
};
const framework = tests && parser ? frameworkFor(config) : null;
// PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest,
@@ -817,7 +825,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
maxChars: consoleCharLimit(),
onLine: (text, kind) => {
if (pluginTests && kind !== "system") pluginTests.feed(text);
if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) tests.apply(parser.feed(text));
if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) applyTests(parser.feed(text));
if (kind !== "system") for (const l of runtime.lineListeners) l(text);
if (kind !== "system") runtime.dotnetReports?.feed(text);
},
@@ -1044,6 +1052,7 @@ async function startRunIn(
stopped: false,
httpPort: undefined,
backgroundCheck: undefined,
watching: undefined,
};
const updated = session;
useRun.setState((s) => ({
@@ -1120,6 +1129,20 @@ async function startRunIn(
};
try {
let launch = options.launch ?? config;
// Jest / Vitest "Watch for changes". Debug and derived runs (Rerun Failed, selected tests,
// Update Snapshot) run the tests once.
if (!options.launch && !baseConfig && launch.watch && launch.isTest && frameworkFor(launch) === "js") {
const watched = watchLaunch(launch, await packageScript(launch));
if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null;
if (watched) {
launch = watched;
patchSession(sessionId, { watching: true });
} else
enqueue(sessionId, {
kind: "system",
text: tx`Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n`,
});
}
// A Maven/Gradle configuration's own command is its build; Rebuild adds clean.
if (!options.launch) launch = applyBuildPolicyToCommand(launch);
// "Build and run using: Gradle": the module's Gradle build compiles and launches it.
@@ -1652,6 +1675,14 @@ export function configRemoved(id: string): boolean {
return listedConfigIds.has(id) && !useRun.getState().configs.some((c) => c.id === id);
}
/** "Rerun Automatically": a Jest / Vitest run in watch mode in the same tab; off stops the watcher. */
export function toggleRerunAutomatically(sessionId: string) {
const session = getSession(sessionId);
if (!session) return;
if (session.watching && isLive(session)) void stopSession(sessionId);
else void startRun({ ...baseConfigOf(session), watch: true }, sessionId);
}
export function rerunSession(sessionId: string) {
const session = getSession(sessionId);
if (session) void startRun(rerunConfig(session), sessionId, session.baseConfig && baseConfigOf(session));
+3 -2
Переглянути файл
@@ -58,7 +58,8 @@ export type Framework =
| "zig"
| "auto";
type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & Partial<Pick<RunConfig, "testRunner" | "env">>;
type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> &
Partial<Pick<RunConfig, "testRunner" | "env" | "watch">>;
export function frameworkFor(config: FrameworkConfig): Framework {
const cmd = [config.command, ...config.args].join(" ");
@@ -172,7 +173,7 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser {
case "cargo":
return cargoParser();
case "js":
return jsParser();
return jsParser(!!config.watch);
case "playwright":
return playwrightParser();
case "node-test":
+23 -1
Переглянути файл
@@ -37,7 +37,29 @@ function counts(text: string) {
return out;
}
export function jsParser(): TestOutputParser {
/** `watch`: after a run's summary, the next output starts a new cycle (`reset`). */
export function jsParser(watch = false): TestOutputParser {
const parser = runParser();
if (!watch) return parser;
let ended = false;
return {
feed(line) {
const events = parser.feed(line);
if (ended && events.some((e) => e.type !== "summary")) {
ended = false;
events.unshift({ type: "reset" });
}
// The counts line (`Tests: …`) ends the cycle; `Time:` / `Duration` follow it.
if (!ended && events.some((e) => e.type === "summary" && e.durationMs === undefined)) {
ended = true;
events.push({ type: "end" });
}
return events;
},
};
}
function runParser(): TestOutputParser {
let file: string | null = null;
/** Jest verbose describe blocks: indentation → name. */
let describes: Array<{ indent: number; name: string }> = [];
+9
Переглянути файл
@@ -168,6 +168,15 @@ export class TestResults {
case "summary":
this.summary = { ...this.summary, ...stripUndefined(e) };
break;
case "reset":
this.roots.length = 0;
this.byId.clear();
this.summary = {};
this.finished = false;
break;
case "end":
this.finished = true;
break;
}
}
}
+5 -1
Переглянути файл
@@ -21,7 +21,11 @@ export type TestEvent =
| { type: "result"; path: string[]; status: Exclude<TestStatus, "running">; durationMs?: number }
| { type: "location"; path: string[]; location: TestLocation }
| { type: "output"; path: string[]; line: string }
| { type: "summary"; passed?: number; failed?: number; skipped?: number; durationMs?: number };
| { type: "summary"; passed?: number; failed?: number; skipped?: number; durationMs?: number }
/** A watch mode cycle begins: its results replace the previous ones. */
| { type: "reset" }
/** A watch mode cycle has reported all its results. */
| { type: "end" };
export interface TestOutputParser {
feed(line: string): TestEvent[];
+152
Переглянути файл
@@ -0,0 +1,152 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { jsParser, parseAll, TestResults } from "./index";
import { watchLaunch } from "./watch";
const cfg = (over: Partial<RunConfig>): RunConfig =>
({
id: "t",
name: "t",
kind: "npm",
command: "npm",
args: ["run", "test"],
env: {},
isTest: true,
...over,
}) as RunConfig;
const JEST_CYCLES = `PASS src/sum.test.js
sum
✓ adds (3 ms)
✓ zero (1 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 0.861 s
Ran all test suites.
FAIL src/sum.test.js
sum
✕ adds (4 ms)
✓ zero (1 ms)
● sum › adds
expect(received).toBe(expected)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Time: 0.5 s
Ran all test suites.`;
const VITEST_CYCLES = ` DEV v2.1.9 /p
✓ tests/cart.test.ts (5 tests | 1 skipped) 96ms
Test Files 1 passed (1)
Tests 4 passed | 1 skipped (5)
Duration 1.11s
PASS Waiting for file changes...
RERUN src/money.ts x2
✓ tests/cart.test.ts (5 tests | 1 skipped) 38ms
Test Files 1 passed (1)
Tests 4 passed | 1 skipped (5)
Duration 133ms
PASS Waiting for file changes...`;
describe("watch mode cycles", () => {
it("replaces the tree with each Jest cycle", () => {
const tests = new TestResults();
tests.apply(parseAll(jsParser(true), JEST_CYCLES));
expect(tests.roots.map((r) => r.name)).toEqual(["src/sum.test.js"]);
expect(tests.roots[0]!.children[0]!.children.map((c) => [c.name, c.own])).toEqual([
["adds", "failed"],
["zero", "passed"],
]);
expect(tests.counts()).toMatchObject({ passed: 1, failed: 1, total: 2 });
expect(tests.finished).toBe(true);
});
it("ends each cycle once and starts the next one unfinished", () => {
const parser = jsParser(true);
const tests = new TestResults();
const lines = JEST_CYCLES.split("\n");
const firstEnd = lines.findIndex((l) => l.startsWith("Tests:"));
for (const l of lines.slice(0, firstEnd + 3)) tests.apply(parser.feed(l));
expect(tests.finished).toBe(true);
tests.apply(parser.feed("FAIL src/sum.test.js"));
expect(tests.finished).toBe(false);
expect(parseAll(jsParser(true), JEST_CYCLES).filter((e) => e.type === "end")).toHaveLength(2);
});
it("replaces the tree with each Vitest cycle", () => {
const events = parseAll(jsParser(true), VITEST_CYCLES);
expect(events.filter((e) => e.type === "reset")).toHaveLength(1);
const tests = new TestResults();
tests.apply(events);
expect(tests.roots).toHaveLength(1);
expect(tests.summary).toMatchObject({ passed: 4, skipped: 1, durationMs: 133 });
});
it("keeps a single run's results without watch", () => {
expect(parseAll(jsParser(), JEST_CYCLES).some((e) => e.type === "reset")).toBe(false);
});
});
const script = (text: string, pre = false) => ({ text, pre });
describe("watchLaunch", () => {
it("appends the watch flag to a package.json script", () => {
expect(watchLaunch(cfg({}), script("tsc && jest", true))?.args).toEqual(["run", "test", "--", "--watchAll"]);
expect(watchLaunch(cfg({ command: "pnpm" }), script("vitest --config v.ts"))?.args).toEqual([
"run",
"test",
"--watch",
]);
});
it("starts `vitest watch` through the package manager for a script running `vitest run`", () => {
const watched = watchLaunch(
cfg({ args: ["run", "test", "--", "tests/a.test.ts"] }),
script("CI=1 vitest run --dir src"),
);
expect(watched).toMatchObject({
command: "npm",
args: ["exec", "--", "vitest", "watch", "--dir", "src", "tests/a.test.ts"],
env: { CI: "1" },
});
expect(watchLaunch(cfg({ command: "yarn" }), script("vitest run"))?.args).toEqual(["vitest", "watch"]);
expect(watchLaunch(cfg({ command: "pnpm" }), script("vitest run"))?.args).toEqual(["exec", "vitest", "watch"]);
});
it("runs once when the watch flag would reach another tool or steps would be skipped", () => {
expect(watchLaunch(cfg({}), script("jest && eslint ."))).toBeNull();
expect(watchLaunch(cfg({}), script("tsc && vitest run"))).toBeNull();
expect(watchLaunch(cfg({}), script("vitest run", true))).toBeNull();
expect(watchLaunch(cfg({}), script("cross-env CI=1 vitest run"))).toBeNull();
});
it("changes the runner's own command line", () => {
expect(
watchLaunch(cfg({ kind: "node", command: "npx", args: ["vitest", "run", "a.test.ts"] }), null)?.args,
).toEqual(["vitest", "watch", "a.test.ts"]);
expect(watchLaunch(cfg({ kind: "node", command: "npx", args: ["jest", "-t", "^x$"] }), null)?.args).toEqual([
"jest",
"-t",
"^x$",
"--watchAll",
]);
});
it("is null without Jest or Vitest", () => {
expect(watchLaunch(cfg({}), script("mocha"))).toBeNull();
expect(watchLaunch(cfg({}), null)).toBeNull();
// `bun test` is Bun's own runner, not the `test` script.
expect(watchLaunch(cfg({ kind: "bun", command: "bun", args: ["test"] }), script("vitest"))).toBeNull();
});
});
+91
Переглянути файл
@@ -0,0 +1,91 @@
/**
* Jest / Vitest "Watch for changes": the launch that keeps the runner watching, so each
* edit reruns the tests in the same tab (`jsParser` starts a new cycle after each summary).
*/
import { call, commands, type RunConfig } from "@/platform/ipc";
import { commandName } from "../commandName";
import { parseArgs } from "../configs";
import { runDirectory } from "../navigate";
import { appendScriptArgs } from "../scriptArgs";
type Runner = "jest" | "vitest";
/** Jest's `--watch` needs git or hg; `--watchAll` works everywhere. */
const WATCH_FLAG: Record<Runner, string> = { jest: "--watchAll", vitest: "--watch" };
const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
const CHAIN = new Set(["&&", "||", ";", "|"]);
function runnerOf(token: string): Runner | null {
const name = commandName(token).replace(/\.[cm]?js$/, "");
return name === "jest" || name === "vitest" ? name : null;
}
/** `npm run test` / `pnpm test`: the package.json script it runs (`bun test` is Bun's own runner). */
function scriptName(config: RunConfig): string | null {
const pm = commandName(config.command);
if (!["npm", "bun"].includes(config.kind) || !PACKAGE_MANAGERS.includes(pm)) return null;
if (config.args[0] === "run") return config.args[1] ?? null;
return pm === "bun" ? null : (config.args[0] ?? null);
}
/** The package.json script a configuration runs: its text, and whether a `pre` script runs before it. */
export interface PackageScript {
text: string;
pre: boolean;
}
export async function packageScript(config: RunConfig): Promise<PackageScript | null> {
const name = scriptName(config);
if (!name) return null;
try {
const pkg = JSON.parse(await call(commands.fsReadText(`${runDirectory(config.cwd)}/package.json`))) as {
scripts?: Record<string, unknown>;
};
const text = pkg.scripts?.[name];
return typeof text === "string" ? { text, pre: typeof pkg.scripts?.[`pre${name}`] === "string" } : null;
} catch {
return null;
}
}
/** The package manager's way to start a package's binary (Yarn PnP included). */
const EXEC: Record<string, string[]> = { npm: ["exec", "--"], pnpm: ["exec"], yarn: [], bun: ["x"] };
const ASSIGNMENT = /^\w+=/;
/**
* `config` launched in watch mode; null when that can't be done and the tests run once: no Jest
* or Vitest, or a script that runs more after it (`jest && eslint .`). `script`: see {@link packageScript}.
*/
export function watchLaunch(config: RunConfig, script: PackageScript | null): RunConfig | null {
const name = scriptName(config);
if (!name) {
const cmd = [config.command, ...config.args];
const at = cmd.findIndex((t) => runnerOf(t));
if (at < 0) return null;
const runner = runnerOf(cmd[at]!)!;
// `vitest run` never watches, whatever the flags: `vitest watch` does.
if (runner === "vitest" && cmd[at + 1] === "run") cmd[at + 1] = "watch";
else cmd.push(WATCH_FLAG[runner]);
return { ...config, command: cmd[0]!, args: cmd.slice(1) };
}
if (script === null) return null;
const words = parseArgs(script.text);
const at = words.findIndex((w) => runnerOf(w));
if (at < 0) return null;
const runner = runnerOf(words[at]!)!;
const rest = words.slice(at + 1);
// The package manager adds arguments at the end of the script: the runner must be its last command.
if (rest.some((w) => CHAIN.has(w))) return null;
if (runner === "jest" || rest[0] !== "run")
return { ...config, args: appendScriptArgs(config.command, config.args, [WATCH_FLAG[runner]]) };
// `vitest run` ignores `--watch`: the package manager starts `vitest watch` with the script's
// variables and options, unless the script does more (a `pre` script, `tsc && …`, `cross-env …`).
const before = words.slice(0, at);
if (script.pre || !before.every((w) => ASSIGNMENT.test(w))) return null;
const env = { ...config.env };
for (const w of before) env[w.slice(0, w.indexOf("="))] = w.slice(w.indexOf("=") + 1);
const passed = config.args.slice(config.args[0] === "run" ? 2 : 1);
if (passed[0] === "--") passed.shift();
const exec = EXEC[commandName(config.command)] ?? [];
return { ...config, args: [...exec, "vitest", "watch", ...rest.slice(1), ...passed], env };
}
+88
Переглянути файл
@@ -0,0 +1,88 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { RunConfig } from "@/platform/ipc";
const ipc = vi.hoisted(() => ({
runStart: vi.fn(async (_config: RunConfig) => ({ status: "ok", data: { id: 7, pty: false } })),
runStop: vi.fn(async () => ({ status: "ok", data: null })),
fsReadText: vi.fn(async () => ({ status: "ok", data: JSON.stringify({ scripts: { test: ipc.script } }) })),
script: "vitest run",
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: ((m: unknown) => void) | null = null;
},
}));
import { useProject } from "@/platform/project";
import {
provideNotificationService,
provideToolWindowService,
type ToolWindowService,
} from "@/workbench/contributions";
import { resetRuns, runtime, startRun, toggleRerunAutomatically, useRun } from "./store";
const config = (over: Partial<RunConfig> = {}): RunConfig =>
({
id: "npm:test",
name: "npm run test",
kind: "npm",
command: "npm",
args: ["run", "test"],
cwd: null,
env: {},
isTest: true,
...over,
}) as RunConfig;
const launched = () => ipc.runStart.mock.calls.map(([c]) => [c.command, ...c.args].join(" "));
beforeEach(() => {
vi.clearAllMocks();
ipc.script = "vitest run";
useProject.setState({ settings: null, project: { root: "/p" } as never });
provideNotificationService({ notify: vi.fn() });
provideToolWindowService({ show: vi.fn(), hide: vi.fn() } as unknown as ToolWindowService);
});
afterEach(() => resetRuns());
it("runs as configured without Watch for changes", async () => {
await startRun(config(), undefined, undefined, { prepared: true });
expect(launched()).toEqual(["npm run test"]);
expect(ipc.fsReadText).not.toHaveBeenCalled();
});
it("launches the watcher, and Rerun Automatically stops it", async () => {
const session = await startRun(config({ watch: true }), undefined, undefined, { prepared: true });
expect(ipc.fsReadText).toHaveBeenCalledWith("/p/package.json");
expect(launched()).toEqual(["npm exec -- vitest watch"]);
expect(useRun.getState().sessions[0]).toMatchObject({ status: "running", watching: true });
toggleRerunAutomatically(session!.id);
await vi.waitFor(() => expect(ipc.runStop).toHaveBeenCalledWith(7));
});
it("Rerun Automatically restarts a finished tab in watch mode", async () => {
const session = await startRun(config(), undefined, undefined, { prepared: true });
useRun.setState((s) => ({ sessions: s.sessions.map((x) => ({ ...x, status: "finished" as const })) }));
toggleRerunAutomatically(session!.id);
await vi.waitFor(() => expect(launched()).toEqual(["npm run test", "npm exec -- vitest watch"]));
expect(useRun.getState().sessions).toHaveLength(1);
expect(useRun.getState().sessions[0]!.config.watch).toBe(true);
});
it("runs derived runs (Rerun Failed, selected tests, Update Snapshot) once", async () => {
const session = await startRun(config({ watch: true }), undefined, config({ watch: true }), { prepared: true });
expect(launched()).toEqual(["npm run test"]);
expect(session?.watching).toBeUndefined();
});
it("runs once, and says so, when the script runs more than the tests", async () => {
ipc.script = "jest && eslint .";
const session = await startRun(config({ watch: true }), undefined, undefined, { prepared: true });
expect(launched()).toEqual(["npm run test"]);
expect(useRun.getState().sessions[0]!.watching).toBeUndefined();
await vi.waitFor(() => expect(runtime(session!.id)!.console.text()).toContain("the tests run once"));
});
+5 -1
Переглянути файл
@@ -4081,5 +4081,9 @@
"Dependencies changed since the last install": "Dependencies changed since the last install",
"Run '{command}' in '{rel}' to install them.": "Run '{command}' in '{rel}' to install them.",
"Run '{command}' to install them.": "Run '{command}' to install them.",
"Install Node.js Dependencies": "Install Node.js Dependencies"
"Install Node.js Dependencies": "Install Node.js Dependencies",
"Watch for changes": "Watch for changes",
"Rerun Automatically": "Rerun Automatically",
"Debug runs the tests once, without watching.": "Debug runs the tests once, without watching.",
"Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n": "Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n"
}
+5 -1
Переглянути файл
@@ -10482,5 +10482,9 @@
"Debug '{name}' with {title}": "使用 {title} 调试 '{name}'",
"Run with {title}": "使用 {title} 运行",
"Debug with {title}": "使用 {title} 调试",
"Launches the selected configuration with the Java agent of {pluginName}": "使用 {pluginName} 的 Java 代理启动所选配置"
"Launches the selected configuration with the Java agent of {pluginName}": "使用 {pluginName} 的 Java 代理启动所选配置",
"Watch for changes": "监视更改",
"Rerun Automatically": "自动重新运行",
"Debug runs the tests once, without watching.": "调试时测试只运行一次,不监视更改。",
"Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n": "监视模式要求命令或脚本以 Jest 或 Vitest 结尾:测试只运行一次。\n"
}
+7
Переглянути файл
@@ -0,0 +1,7 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 9.50215C9 8.32441 10.2951 7.60608 11.2942 8.22967L15.2962 10.7275C16.2372 11.3149 16.2372 12.6851 15.2962 13.2725L11.2942 15.7703C10.2951 16.3939 9 15.6756 9 14.4978V9.50215ZM10.7647 9.07799C10.4317 8.87013 10 9.10957 10 9.50215V14.4978C10 14.8904 10.4317 15.1298 10.7647 14.922L14.7667 12.4241C15.0804 12.2284 15.0804 11.7716 14.7667 11.5758L10.7647 9.07799Z" fill="#208A3C"/>
<path d="M10 9.50226C10 9.10968 10.4317 8.87024 10.7647 9.0781L14.7667 11.5759C15.0804 11.7717 15.0804 12.2285 14.7667 12.4243L10.7647 14.9221C10.4317 15.13 10 14.8905 10 14.4979V9.50226Z" fill="#F2FCF3"/>
<path d="M10.5 2C10.2239 2 10 2.22386 10 2.5V3.08902C9.99986 3.09587 9.99986 3.10271 10 3.10954V5.5C10 5.77614 10.2239 6 10.5 6C10.7761 6 11 5.77614 11 5.5V3.99951C12.215 4.91216 13 6.36471 13 7.99998C13 8.03829 12.9996 8.07651 12.9987 8.11462L13.958 8.71338C13.9857 8.47944 14 8.24138 14 7.99998C14 5.91232 12.9337 4.0744 11.3177 3H13.5C13.7761 3 14 2.77614 14 2.5C14 2.22386 13.7761 2 13.5 2H10.5Z" fill="#6C707E"/>
<path d="M6 10.5C6 10.2239 5.77614 10 5.5 10C5.22386 10 5 10.2239 5 10.5V12.0004C3.78495 11.0878 3 9.63525 3 7.99998C3 5.54954 4.76326 3.50989 7.09033 3.08244C7.36193 3.03255 7.54166 2.77193 7.49177 2.50033C7.44188 2.22873 7.18127 2.049 6.90967 2.09889C4.1165 2.61195 2 5.05827 2 7.99998C2 10.0877 3.06633 11.9256 4.68238 13H2.5C2.22386 13 2 13.2239 2 13.5C2 13.7761 2.22386 14 2.5 14H5.5C5.77614 14 6 13.7761 6 13.5V12.911C6.00014 12.9041 6.00014 12.8972 6 12.8904V10.5Z" fill="#6C707E"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 1.7 KiB

+7
Переглянути файл
@@ -0,0 +1,7 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M9 9.50215C9 8.32441 10.2951 7.60608 11.2942 8.22967L15.2962 10.7275C16.2372 11.3149 16.2372 12.6851 15.2962 13.2725L11.2942 15.7703C10.2951 16.3939 9 15.6756 9 14.4978V9.50215ZM10.7647 9.07799C10.4317 8.87013 10 9.10957 10 9.50215V14.4978C10 14.8904 10.4317 15.1298 10.7647 14.922L14.7667 12.4241C15.0804 12.2284 15.0804 11.7716 14.7667 11.5758L10.7647 9.07799Z" fill="#57965C"/>
<path d="M10 9.50226C10 9.10968 10.4317 8.87024 10.7647 9.0781L14.7667 11.5759C15.0804 11.7717 15.0804 12.2285 14.7667 12.4243L10.7647 14.9221C10.4317 15.13 10 14.8905 10 14.4979V9.50226Z" fill="#253627"/>
<path d="M10.5 2C10.2239 2 10 2.22386 10 2.5V3.08902C9.99986 3.09587 9.99986 3.10271 10 3.10954V5.5C10 5.77614 10.2239 6 10.5 6C10.7761 6 11 5.77614 11 5.5V3.99951C12.215 4.91216 13 6.36471 13 7.99998C13 8.03829 12.9996 8.07651 12.9987 8.11462L13.958 8.71338C13.9857 8.47944 14 8.24138 14 7.99998C14 5.91232 12.9337 4.0744 11.3177 3H13.5C13.7761 3 14 2.77614 14 2.5C14 2.22386 13.7761 2 13.5 2H10.5Z" fill="#CED0D6"/>
<path d="M6 10.5C6 10.2239 5.77614 10 5.5 10C5.22386 10 5 10.2239 5 10.5V12.0004C3.78495 11.0878 3 9.63525 3 7.99998C3 5.54954 4.76326 3.50989 7.09033 3.08244C7.36193 3.03255 7.54166 2.77193 7.49177 2.50033C7.44188 2.22873 7.18127 2.049 6.90967 2.09889C4.1165 2.61195 2 5.05827 2 7.99998C2 10.0877 3.06633 11.9256 4.68238 13H2.5C2.22386 13 2 13.2239 2 13.5C2 13.7761 2.22386 14 2.5 14H5.5C5.77614 14 6 13.7761 6 13.5V12.911C6.00014 12.9041 6.00014 12.8972 6 12.8904V10.5Z" fill="#CED0D6"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 1.7 KiB

+1
Переглянути файл
@@ -512,6 +512,7 @@ const ICONS = {
"gutter-javadoc-edit": "gutter/javadocEdit",
stop: "run/stop",
rerun: "run/rerun",
"rerun-automatically": "actions/rerunAutomatically",
"hot-reload": "openidea/general/hotReload",
"rerun-filled": "run/rerun_stroke",
"restart-debug": "run/restartDebug",