diff --git a/src/features/run/testing/js.test.ts b/src/features/run/testing/js.test.ts new file mode 100644 index 0000000000..5bdcef63d5 --- /dev/null +++ b/src/features/run/testing/js.test.ts @@ -0,0 +1,342 @@ +import { describe, expect, it } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { jsParser, parseAll, TestResults } from "./index"; +import { failedTestPaths, rerunFailedConfigs } from "./rerun"; + +const cfg = (args: string[], command = "pnpm", kind = "npm"): RunConfig => ({ + id: "npm:test", + name: "npm test", + kind, + command, + args, + cwd: null, + env: {}, + detected: true, + isTest: true, + debugAdapter: null, +}); +const results = (text: string) => { + const r = new TestResults(); + r.apply(parseAll(jsParser(), text)); + return r; +}; +const at = (r: TestResults, ...path: string[]) => r.get(path.join("\u0000")); +const rerun = (config: RunConfig, r: TestResults) => + (rerunFailedConfigs(config, failedTestPaths(r)) as RunConfig[]).map((c) => c.args); + +/** Vitest 5.0.5, default reporter (code frames left out). */ +const DETAILS = (label = (_file: string) => "") => ` +⎯⎯⎯⎯⎯⎯⎯ Failed Tests 4 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL ${label("my dir/some file.test.ts")}my dir/some file.test.ts > a > b > c > spaces +AssertionError: expected 1 to be 4 // Object.is equality + ❯ my dir/some file.test.ts:2:80 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/4]⎯ + + FAIL ${label("my dir/some file.test.ts")}my dir/some file.test.ts > a > x › y +AssertionError: expected 1 to be 5 // Object.is equality + ❯ my dir/some file.test.ts:2:127 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[2/4]⎯ + + FAIL ${label("app/(auth)/login.test.ts")}app/(auth)/login.test.ts > login > rejects x > 0 +AssertionError: expected 1 to be 2 // Object.is equality + ❯ app/(auth)/login.test.ts:2:87 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[3/4]⎯ + + FAIL ${label("app/[id]/page.test.ts")}app/[id]/page.test.ts > top > level +AssertionError: expected 1 to be 3 // Object.is equality + ❯ app/[id]/page.test.ts:2:37 + +⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[4/4]⎯ + + + Test Files 3 failed | 1 passed (4) + Tests 4 failed | 5 passed (9) + Duration 184ms (transform 57ms) +`; +const VITEST_5 = ` RUN v5.0.5 /p + + ✓ lib/login.test.ts (2 tests) 1ms +stdout | app/(auth)/login.test.ts > login > rejects x > 0 +hello + + ❯ app/[id]/page.test.ts (2 tests | 1 failed) 3ms + × top > level 3ms + ✓ plain 0ms + ❯ app/(auth)/login.test.ts (2 tests | 1 failed) 4ms + ❯ login (2) + × rejects x > 0 3ms + ✓ ok 0ms + ❯ my dir/some file.test.ts (3 tests | 2 failed) 4ms + ❯ a (3) + ❯ b > c (1) + × spaces 3ms + × x › y 0ms + ✓ fine 0ms +${DETAILS()}`; + +const TITLES: string[][] = [ + ["app/[id]/page.test.ts", "top > level"], + ["app/(auth)/login.test.ts", "login", "rejects x > 0"], + ["my dir/some file.test.ts", "a", "b > c", "spaces"], + ["my dir/some file.test.ts", "a", "x › y"], +]; + +describe("Vitest files and titles", () => { + it("reads them from the tree (Vitest 5)", () => { + const r = results(VITEST_5); + expect(r.roots.map((n) => n.name).sort()).toEqual([ + "app/(auth)/login.test.ts", + "app/[id]/page.test.ts", + "lib/login.test.ts", + "my dir/some file.test.ts", + ]); + expect(failedTestPaths(r)).toEqual(TITLES); + for (const [path, line, col] of [ + [TITLES[0]!, 2, 37], + [TITLES[1]!, 2, 87], + [TITLES[2]!, 2, 80], + [TITLES[3]!, 2, 127], + ] as const) + expect(at(r, ...path)?.location).toMatchObject({ path: path[0], line, col }); + expect(at(r, ...TITLES[1]!)?.output).toContain("hello"); + expect(at(r, ...TITLES[1]!)?.output).toContain("AssertionError: expected 1 to be 2 // Object.is equality"); + expect(r.counts()).toMatchObject({ failed: 4, passed: 5 }); + expect(r.get("lib/login.test.ts")?.own).toBe("passed"); + }); + + it("gives a title the same node when its details come first (stderr)", () => { + const r = results(` RUN v5.0.5 /p\n${DETAILS()}${VITEST_5}`); + expect(failedTestPaths(r)).toHaveLength(4); + }); + + it("leaves out suites Vitest 4 doesn't print, and takes them from the details", () => { + const r = results(` RUN v4.0.8 /p + + ❯ app/(auth)/login.test.ts (2 tests | 1 failed) 3ms + × rejects x > 0 3ms + ✓ ok 0ms + + FAIL app/(auth)/login.test.ts > login > rejects x > 0 +AssertionError: expected 1 to be 2 +`); + expect(failedTestPaths(r)).toEqual([TITLES[1]]); + }); + + it("reads passing suites of the tree reporter", () => { + const r = results(` RUN v5.0.5 /p + + ✓ lib/login.test.ts (2 tests) 1ms + ✓ login (2) + ✓ rejects x > 0 0ms + ✓ ok (2) 0ms +`); + expect(at(r, "lib/login.test.ts", "login", "rejects x > 0")?.own).toBe("passed"); + expect(at(r, "lib/login.test.ts", "login", "ok (2)")?.own).toBe("passed"); + expect(r.counts().passed).toBe(2); + }); + + it("reads verbose and Vitest 3 lines", () => { + const verbose = results(` RUN v5.0.5 /p + + × my dir/some file.test.ts > a > fine 1ms + ✓ app/(auth)/login.test.ts > login > ok 0ms +`); + expect(at(verbose, "my dir/some file.test.ts", "a", "fine")?.own).toBe("failed"); + expect(at(verbose, "app/(auth)/login.test.ts", "login", "ok")?.own).toBe("passed"); + const v3 = results(` RUN v3.2.4 /p + + ❯ app/(auth)/login.test.ts (2 tests | 1 failed) 4ms + × login > x › y 3ms + ✓ login > ok 0ms + + FAIL app/(auth)/login.test.ts > login > x › y +AssertionError: expected 1 to be 2 +`); + expect(failedTestPaths(v3)).toEqual([["app/(auth)/login.test.ts", "login", "x › y"]]); + }); + + it("gives a file that cannot be loaded its error", () => { + const r = results(` RUN v5.0.5 /p + + ❯ app/(auth)/bad.test.ts (0 test) + +⎯⎯⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯ + + FAIL app/(auth)/bad.test.ts [ app/(auth)/bad.test.ts ] +Error: Cannot find module './nope' + ❯ app/(auth)/bad.test.ts:1:1 +`); + expect(failedTestPaths(r)).toEqual([["app/(auth)/bad.test.ts"]]); + expect(r.get("app/(auth)/bad.test.ts")?.output).toContain("Error: Cannot find module './nope'"); + }); +}); + +describe("Vitest projects", () => { + const PROJECTS = ` RUN v5.0.5 /p + + ✓ |unit| lib/login.test.ts (2 tests) 1ms + ❯ |web ui| lib/login.test.ts (2 tests | 1 failed) 1ms + ❯ login (2) + × ok 3ms +stdout | app/(auth)/login.test.ts > login > rejects x > 0 +hello + + ❯ |web ui| app/(auth)/login.test.ts (2 tests | 1 failed) 4ms + ❯ login (2) + × rejects x > 0 3ms + + FAIL |web ui| lib/login.test.ts > login > ok +AssertionError: expected 1 to be 9 + ❯ lib/login.test.ts:2:8 + + FAIL |web ui| app/(auth)/login.test.ts > login > rejects x > 0 +AssertionError: expected 1 to be 2 + ❯ app/(auth)/login.test.ts:2:87 + +`; + it("keeps a file's runs apart, under the file", () => { + const r = results(PROJECTS); + expect(r.roots.map((n) => n.name)).toEqual(["lib/login.test.ts", "app/(auth)/login.test.ts"]); + expect(at(r, "lib/login.test.ts", "|unit|")?.own).toBe("passed"); + expect(failedTestPaths(r)).toEqual([ + ["lib/login.test.ts", "|web ui|", "login", "ok"], + ["app/(auth)/login.test.ts", "|web ui|", "login", "rejects x > 0"], + ]); + const output = at(r, "app/(auth)/login.test.ts", "|web ui|", "login", "rejects x > 0")!.output; + expect(output[0]).toBe("hello"); + expect(r.get("app/(auth)/login.test.ts")!.children).toHaveLength(1); + }); + + it("reruns in the project that failed", () => { + expect(rerun(cfg(["vitest", "run", "--project", "unit"], "npx", "npm"), results(PROJECTS))).toEqual([ + [ + "vitest", + "run", + "lib/login.test.ts", + "app/(auth)/login.test.ts", + "-t", + "^(?:login (?:[>\\u203a] )?ok|login (?:[>\\u203a] )?rejects x > 0)$", + "--project", + "web ui", + ], + ]); + }); +}); + +describe("Jest files and titles", () => { + /** Jest 30.5 \`--verbose\` (code frames left out). */ + const JEST = `FAIL app/[id]/page.test.js + ✕ top > level (1 ms) + ✓ plain + + ● top > level + + expect(received).toBe(expected) // Object.is equality + + at Object.toBe (app/[id]/page.test.js:2:37) + +FAIL app/(auth)/login.test.js (5.2 s) + login + ✕ rejects x > 0 (2 ms) + ✓ ok + + ● login › rejects x > 0 + + expect(received).toBe(expected) // Object.is equality + + at Object.toBe (app/(auth)/login.test.js:2:87) + +FAIL src/some file.test.js + a + ✕ x › y + ✓ fine + b > c + ✕ spaces + + ● a › x › y + + expect(received).toBe(expected) // Object.is equality + + at Object.toBe (src/some file.test.js:2:127) + + ● a › b > c › spaces + + expect(received).toBe(expected) // Object.is equality + + at Object.toBe (/p/(auth)../../../../../src/some file.test.js:2:80) + +PASS lib/login.test.js + login + ✓ rejects x > 0 + ✓ ok + +Test Suites: 3 failed, 1 passed, 4 total +Tests: 4 failed, 5 passed, 9 total +Time: 0.149 s, estimated 1 s +`; + it("reads them", () => { + const r = results(JEST); + expect(failedTestPaths(r)).toEqual([ + ["app/[id]/page.test.js", "top > level"], + ["app/(auth)/login.test.js", "login", "rejects x > 0"], + ["src/some file.test.js", "a", "x › y"], + ["src/some file.test.js", "a", "b > c", "spaces"], + ]); + expect(at(r, "app/(auth)/login.test.js", "login", "rejects x > 0")?.location).toMatchObject({ + path: "app/(auth)/login.test.js", + line: 2, + col: 87, + }); + expect(at(r, "src/some file.test.js", "a", "x › y")?.location).toMatchObject({ path: "src/some file.test.js" }); + // Jest misprints absolute paths with parentheses: no such file. + expect(at(r, "src/some file.test.js", "a", "b > c", "spaces")?.location).toBeUndefined(); + expect(r.counts()).toMatchObject({ failed: 4, passed: 5 }); + }); + + it("leaves out the project's display name", () => { + const r = results(`PASS unit lib/login.test.js\nFAIL web ui app/(auth)/login.test.js\n ● login › fails\n`); + expect(r.roots.map((n) => n.name)).toEqual(["lib/login.test.js", "app/(auth)/login.test.js"]); + }); + + it("doesn't take a file's console output for a failed test", () => { + const r = results(`PASS lib/login.test.js + ● Console + + console.log + hello + +Tests: 2 passed, 2 total +`); + expect(failedTestPaths(r)).toEqual([]); + expect(r.get("lib/login.test.js")?.own).toBe("passed"); + }); +}); + +describe("rerun of Vitest and Jest tests", () => { + const paths = [["app/(auth)/login.test.ts", "login", "rejects x", "0"]]; + const args = (config: RunConfig) => (rerunFailedConfigs(config, paths) as RunConfig[]).map((c) => c.args); + // A title split at its own " > " still matches: the runners join suites and test by a space. + const name = "^(?:login (?:[>\\u203a] )?rejects x (?:[>\\u203a] )?0)$"; + + it("names the file as the runner reads it: Vitest as text, Jest as a pattern", () => { + expect(args(cfg(["vitest", "run"], "npx"))).toEqual([["vitest", "run", "app/(auth)/login.test.ts", "-t", name]]); + expect(args(cfg(["jest"], "npx"))).toEqual([["jest", "app/\\(auth\\)/login\\.test\\.ts", "-t", name]]); + }); + + it("names it both ways for a script that may run either", () => { + expect(args(cfg(["run", "test"]))).toEqual([ + ["run", "test", "app/(auth)/login.test.ts", "app/\\(auth\\)/login\\.test\\.ts", "-t", name], + ]); + }); + + it("finds the split title", () => { + const pattern = new RegExp(name); + expect(pattern.test("login rejects x > 0")).toBe(true); + expect(pattern.test("login rejects x 0")).toBe(true); + expect(pattern.test("login rejects x - 0")).toBe(false); + }); +}); diff --git a/src/features/run/testing/js.ts b/src/features/run/testing/js.ts index 0424e395aa..8d709c9137 100644 --- a/src/features/run/testing/js.ts +++ b/src/features/run/testing/js.ts @@ -6,18 +6,30 @@ const FAIL_MARKS = "✕×✗✖"; const SKIP_MARKS = "○↓⊘"; const TODO_MARKS = "✎"; -const TEST_FILE = String.raw`[^\s>()]+\.(?:[cm]?[jt]sx?|vue|svelte|astro)`; -const JEST_FILE_RE = new RegExp(String.raw`^\s*(PASS|FAIL)\s+(${TEST_FILE})(?:\s+\(.*\))?\s*$`); -const VITEST_FAIL_HEADER_RE = new RegExp(String.raw`^\s*FAIL\s+(${TEST_FILE})\s+>\s+(.+?)\s*$`); +const EXTENSION = String.raw`\.(?:[cm]?[jt]sx?|vue|svelte|astro)`; +/** A path in text that ends it: it may hold spaces and parentheses (`app/(auth)/a.test.ts`). */ +const FILE = String.raw`[^\s>](?:[^>]*?[^\s>])?${EXTENSION}`; +const BARE_FILE = String.raw`[^\s>(][^\s>]*?${EXTENSION}`; +/** Vitest labels the files of a project: `|unit| src/a.test.ts`. */ +const PROJECT = String.raw`(?:\|([^|]+)\| )?`; +const RUN_RE = /^\s*(?:RUN|DEV)\s+v(\d+)\./; +const JEST_FILE_RE = new RegExp(String.raw`^\s*(PASS|FAIL)\s+([^>]*\S${EXTENSION})(?:\s+\([^()]*\))?\s*$`); +const VITEST_FAIL_HEADER_RE = new RegExp(String.raw`^\s*FAIL\s+${PROJECT}(${FILE})\s+>\s+(.+?)\s*$`); +const VITEST_FAIL_FILE_RE = new RegExp(String.raw`^\s*FAIL\s+${PROJECT}(${FILE})\s+\[ .+ \]\s*$`); +/** `src/a.test.ts (2 tests | 1 failed) 9ms`, after the mark. */ +const VITEST_FILE_RE = new RegExp(String.raw`^${PROJECT}(${FILE}) \(\d+ tests?(?:\s*\|[^)]*)?\)`); +const VITEST_BARE_FILE_RE = new RegExp(String.raw`^${PROJECT}(${BARE_FILE})(?=\s(?!>)|$)`); +/** Verbose: `src/a.test.ts > suite > test`, after the mark. */ +const VITEST_FLAT_RE = new RegExp(String.raw`^${PROJECT}(${FILE})\s+>\s+(.+)$`); const JEST_FAIL_HEADER_RE = /^\s*● (.+)$/; /** Vitest: `stdout | src/a.test.ts > suite > test` heads the console output of that test, up to a blank line. */ -const VITEST_CONSOLE_RE = new RegExp(String.raw`^(?:stdout|stderr) \| (${TEST_FILE})(?:\s+>\s+(.+?))?\s*$`); -const LOCATION_RE = new RegExp(String.raw`(?:\(|\s|^)(?:file:\/\/)?((?:\/|\.{0,2}\/?)?${TEST_FILE}):(\d+):(\d+)\)?`); +const VITEST_CONSOLE_RE = new RegExp(String.raw`^(?:stdout|stderr) \| ${PROJECT}(${FILE})(?:\s+>\s+(.+?))?\s*$`); +const LOCATION_RE = new RegExp(String.raw`(?:\(|\s|^)(?:file:\/\/)?(${BARE_FILE}):(\d+):(\d+)`); +const JEST_LOCATION_RE = new RegExp(String.raw`\((?:file:\/\/)?([^()].*${EXTENSION}):(\d+):(\d+)\)$`); const JEST_SUMMARY_RE = /^Tests:\s+(.+?)\s*$/; const VITEST_SUMMARY_RE = /^\s*Tests\s+(.+?)\s+\((\d+)\)\s*$/; const DURATION_SUMMARY_RE = /^\s*(?:Time:|Duration)\s+([\d.]+\s*m?s)/; const TRAILING_DURATION_RE = /\s+\(?(\d+(?:\.\d+)?\s?m?s)\)?\s*$/; -const FILE_COUNT_RE = /\s+\((\d+) tests?(?:\s*\|[^)]*)?\)/; function markStatus(mark: string): Exclude | null { if (PASS_MARKS.includes(mark)) return "passed"; @@ -59,21 +71,127 @@ export function jsParser(watch = false): TestOutputParser { }; } +/** A test file's node: its path, then the project when the run names projects. */ +const fileNode = (file: string, project: string | undefined) => (project ? [file, `|${project}|`] : [file]); + +/** The project of a results path, if any. */ +export function vitestProject(path: readonly string[]): string | null { + return /^\|([^|]+)\|$/.exec(path[1] ?? "")?.[1] ?? null; +} + +/** Jest prints a project's display name before the path: what precedes the path's first folder. */ +function jestFile(text: string): string { + const folder = text.indexOf("/"); + return text.slice(text.lastIndexOf(" ", folder < 0 ? text.length : folder) + 1); +} + +/** Console output of a Vitest test, printed before the line that tells the file's project. */ +interface ConsoleBlock { + file: string; + title: string | undefined; + lines: string[]; + node: string[] | null; +} + +const MAX_CONSOLE_LINES = 400; + +/** + * Titles of one file. Reporters join suites and test by ` > ` (Jest: ` › `), which a title may + * hold itself; the tree of a file's tests tells where each name ends. + */ +class Titles { + private readonly paths = new Map(); + /** Tests whose suites weren't printed. */ + private readonly lone = new Set(); + + constructor( + private readonly node: string[], + private readonly separator: string, + ) {} + + /** The path of a test whose names are known, or the one its title was given before. */ + named(names: string[]): string[] { + const title = names.join(this.separator); + const path = this.paths.get(title) ?? [...this.node, ...names]; + this.paths.set(title, path); + return path; + } + + addLone(name: string) { + this.lone.add(name); + } + + titled(title: string): string[] { + const known = this.paths.get(title); + if (known) return known; + const last = [...this.lone].find((name) => title.endsWith(this.separator + name)); + if (last === undefined) return this.named(title.split(this.separator)); + return this.named([...title.slice(0, -(this.separator + last).length).split(this.separator), last]); + } +} + function runParser(): TestOutputParser { - let file: string | null = null; + /** Vitest's major version; 0 for other runners. From 4 on, a file's tests are printed as a tree. */ + let vitest = 0; + let jest = false; + /** The node of the file whose tests the next lines are. */ + let file: string[] | null = null; /** Jest verbose describe blocks: indentation → name. */ let describes: Array<{ indent: number; name: string }> = []; let inVerboseBlock = false; let failure: string[] | null = null; let locationFound = false; - /** The test whose console output (Vitest `stdout | …` block) the next lines are. */ - let consoleOf: string[] | null = null; + /** The Vitest `stdout | …` block the next lines are in, and the ones not reported yet. */ + let consoleOf: ConsoleBlock | null = null; + let consoles: ConsoleBlock[] = []; + const titles = new Map(); + + const titlesOf = (node: string[]) => { + const key = node.join("\u0000"); + let t = titles.get(key); + if (!t) titles.set(key, (t = new Titles(node, jest ? " › " : " > "))); + return t; + }; const startFailure = (path: string[]) => { failure = path; locationFound = false; }; + const locate = (line: string, events: TestEvent[]): boolean => { + const at = failure && !locationFound ? locationIn(line, failure[0]!) : null; + if (!at) return false; + locationFound = true; + events.push({ type: "location", path: failure!, location: { ...at, resolve: "path" } }); + return true; + }; + + /** The console output of `node`'s file is its tests'. */ + const claim = (node: string[]) => { + for (const c of consoles) if (c.file === node[0]) c.node ??= node; + }; + /** Reports the claimed console output: the file's tests have all been printed. */ + const flush = (): TestEvent[] => { + const ready = consoles.filter((c) => c.node); + consoles = consoles.filter((c) => !c.node); + return ready.flatMap(({ node, title, lines }) => { + const path = title ? titlesOf(node!).titled(title) : node!; + return lines.map((line): TestEvent => ({ type: "output", path, line })); + }); + }; + const flushAll = () => { + for (const c of consoles) c.node ??= [c.file]; + return flush(); + }; + const startFile = (node: string[]): TestEvent[] => { + const events = flush(); + claim(node); + file = node; + describes = []; + failure = null; + return events; + }; + return { feed(raw) { const events: TestEvent[] = []; @@ -81,41 +199,53 @@ function runParser(): TestOutputParser { let m: RegExpExecArray | null; if (consoleOf) { - if (line) events.push({ type: "output", path: consoleOf, line: raw }); - else consoleOf = null; + if (!line) consoleOf = null; + else if (consoleOf.lines.length < MAX_CONSOLE_LINES) consoleOf.lines.push(raw); return events; } if ((m = VITEST_CONSOLE_RE.exec(line))) { - consoleOf = [m[1]!, ...(m[2] ? m[2].split(/\s+>\s+/) : [])]; + consoleOf = { file: m[2]!, title: m[3], lines: [], node: m[1] ? fileNode(m[2]!, m[1]) : null }; + consoles.push(consoleOf); + return events; + } + if ((m = RUN_RE.exec(line))) { + vitest = Number(m[1]); return events; } if ((m = JEST_FILE_RE.exec(line))) { - file = m[2]!; - describes = []; + jest = true; + const node = [jestFile(m[2]!)]; + events.push(...startFile(node)); inVerboseBlock = true; - failure = null; - events.push({ type: "result", path: [file], status: m[1] === "PASS" ? "passed" : "failed" }); + events.push({ type: "result", path: node, status: m[1] === "PASS" ? "passed" : "failed" }); return events; } // Vitest separators (`⎯⎯ Failed Tests 1 ⎯⎯`, `⎯⎯[1/2]⎯`) end a failure's details. if (line.trimStart().startsWith("⎯")) { failure = null; - return events; + return flush(); } if ((m = VITEST_FAIL_HEADER_RE.exec(line))) { - const path = [m[1]!, ...m[2]!.split(/\s+>\s+/)]; + events.push(...flush()); + const path = titlesOf(fileNode(m[2]!, m[1])).titled(m[3]!); events.push({ type: "result", path, status: "failed" }); startFailure(path); return events; } + if ((m = VITEST_FAIL_FILE_RE.exec(line))) { + const node = fileNode(m[2]!, m[1]); + events.push(...flush(), { type: "result", path: node, status: "failed" }); + startFailure(node); + return events; + } if ((m = JEST_SUMMARY_RE.exec(line))) { events.push({ type: "summary", ...counts(m[1]!) }); failure = null; return events; } if ((m = VITEST_SUMMARY_RE.exec(line))) { - events.push({ type: "summary", ...counts(m[1]!) }); + events.push(...flushAll(), { type: "summary", ...counts(m[1]!) }); failure = null; return events; } @@ -131,21 +261,12 @@ function runParser(): TestOutputParser { // Vitest: ` ❯ src/a.test.ts:5:13` (failure location) or ` ❯ src/a.test.ts (2 tests | 1 failed)`. if (mark === "❯" || mark === "→") { - const loc = LOCATION_RE.exec(trimmed.slice(2)); - if (loc && failure && !locationFound) { - locationFound = true; - events.push({ - type: "location", - path: failure, - location: { path: loc[1]!, line: Number(loc[2]), col: Number(loc[3]), resolve: "path" }, - }); - return events; - } const body = trimmed.slice(2); - const fm = new RegExp(`^(${TEST_FILE})`).exec(body); - if (fm && FILE_COUNT_RE.test(body)) { - file = fm[1]!; - events.push({ type: "result", path: [file], status: "failed", durationMs: trailingDuration(body) }); + if (locate(body, events)) return events; + if ((m = VITEST_FILE_RE.exec(body))) { + const node = fileNode(m[2]!, m[1]); + events.push(...startFile(node)); + events.push({ type: "result", path: node, status: "failed", durationMs: trailingDuration(body) }); return events; } // Vitest default reporter: ` ❯ Cart (4)` opens a suite with failed tests; its tests follow, indented. @@ -163,35 +284,47 @@ function runParser(): TestOutputParser { let body = trimmed.slice(2); const durationMs = trailingDuration(body); body = body.replace(TRAILING_DURATION_RE, ""); - const fileMatch = new RegExp(`^(${TEST_FILE})(?=\\s|$)`).exec(body); - if (fileMatch) { - const rest = body.slice(fileMatch[0].length); - const sub = /^\s+>\s+(.+)$/.exec(rest); - if (sub) { - // Vitest verbose (flat): `✓ src/a.test.ts > suite > test 2ms`. - events.push({ type: "result", path: [fileMatch[1]!, ...sub[1]!.split(/\s+>\s+/)], status, durationMs }); - } else { - // Vitest file line: `✓ src/a.test.ts (3 tests) 5ms`. - file = fileMatch[1]!; - describes = []; - events.push({ type: "result", path: [file], status, durationMs }); - } + // Vitest file line: `✓ src/a.test.ts (3 tests) 5ms`. A test's title may look like one: they are indented more. + const fileLine = indent <= 1 ? (VITEST_FILE_RE.exec(body) ?? VITEST_BARE_FILE_RE.exec(body)) : null; + if (fileLine) { + const node = fileNode(fileLine[2]!, fileLine[1]); + events.push(...startFile(node), { type: "result", path: node, status, durationMs }); + return events; + } + if (indent <= 1 && (m = VITEST_FLAT_RE.exec(body))) { + // Vitest verbose (flat): `✓ src/a.test.ts > suite > test 2ms`. + const node = fileNode(m[2]!, m[1]); + claim(node); + events.push(...flush(), { type: "result", path: titlesOf(node).titled(m[3]!), status, durationMs }); return events; } - body = body.replace(FILE_COUNT_RE, ""); while (describes.length && describes[describes.length - 1]!.indent >= indent) describes.pop(); - const names = body.split(/\s+(?:>|›)\s+/); - const path = [...(file ? [file] : []), ...describes.map((d) => d.name), ...names]; + if (file && vitest >= 4) { + // Tree reporter: `✓ suite (2)`. A test that ran ends with its duration. + const suite = durationMs === undefined ? /^(.+) \(\d+\)$/.exec(body) : null; + if (suite) { + describes.push({ indent, name: suite[1]! }); + return events; + } + // Vitest 4's default reporter leaves suites out; a failed test's details name them. + if (indent > 3 && !describes.length) { + titlesOf(file).addLone(body); + if (status === "failed") return events; + } + } + const tree = jest || vitest >= 4 || describes.length > 0; + const separator = vitest ? " > " : /\s+(?:>|›)\s+/; + const names = [...describes.map((d) => d.name), ...(tree ? [body] : body.split(separator))]; + const path = file ? titlesOf(file).named(names) : names; events.push({ type: "result", path, status, durationMs }); return events; } if ((m = JEST_FAIL_HEADER_RE.exec(line))) { - const names = m[1]!.split(/\s+›\s+/); - if (names[0] === "Test suite failed to run") { - if (file) startFailure([file]); + if (m[1] === "Console" || m[1]!.startsWith("Test suite failed to run")) { + if (file) startFailure(file); } else { - const path = [...(file ? [file] : []), ...names]; + const path = file ? titlesOf(file).titled(m[1]!) : m[1]!.split(" › "); events.push({ type: "result", path, status: "failed" }); startFailure(path); } @@ -209,23 +342,26 @@ function runParser(): TestOutputParser { if (failure) { events.push({ type: "output", path: failure, line: raw }); - if (!locationFound && !line.includes("node_modules")) { - const loc = /\bat\b/.test(line) || /^\s*❯/.test(line) ? LOCATION_RE.exec(line) : null; - if (loc) { - locationFound = true; - events.push({ - type: "location", - path: failure, - location: { path: loc[1]!, line: Number(loc[2]), col: Number(loc[3]), resolve: "path" }, - }); - } - } + if (!line.includes("node_modules") && /\bat\b/.test(line)) locate(line, events); } return events; }, + end: flushAll, }; } +/** The place a stack line names. `file` is the failing test's: its path may hold spaces. */ +function locationIn(line: string, file: string): { path: string; line: number; col: number } | null { + const own = line.indexOf(`${file}:`); + const at = + own === 0 || /[\s(]/.test(line[own - 1] ?? "") ? /^:(\d+):(\d+)/.exec(line.slice(own + file.length)) : null; + if (own >= 0 && at) return { path: file, line: Number(at[1]), col: Number(at[2]) }; + const m = JEST_LOCATION_RE.exec(line) ?? LOCATION_RE.exec(line); + // Jest misprints absolute paths with parentheses: `/p/app/(auth)../../../login.test.js`. + if (!m || m[1]!.includes(")../")) return null; + return { path: m[1]!, line: Number(m[2]), col: Number(m[3]) }; +} + function trailingDuration(body: string): number | undefined { const m = TRAILING_DURATION_RE.exec(body); return m ? parseDuration(m[1]) : undefined; diff --git a/src/features/run/testing/rerun.test.ts b/src/features/run/testing/rerun.test.ts index d33dfe4ecb..fade5a91c6 100644 --- a/src/features/run/testing/rerun.test.ts +++ b/src/features/run/testing/rerun.test.ts @@ -108,7 +108,7 @@ describe("rerunFailedConfig", () => { "src/a.test.ts", "src/b.test.ts", "-t", - "^(?:math adds \\(1\\+1\\))$", + "^(?:math (?:[>\\u203a] )?adds \\(1\\+1\\))$", ]); }); diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index fb2214e930..cd94d1483c 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -14,6 +14,8 @@ import { goTestParts, withoutGoSelection } from "../goArguments"; import { withMavenTests } from "../mavenTests"; import { frameworkFor } from "./index"; import { cargoRerunArgs, cargoRunOf, isCargoDoctest } from "./cargoRerun"; +import { vitestProject } from "./js"; +import { runnerOf } from "./watch"; import { dotnetFilter } from "./dotnet"; import { xcodeOnlyTesting } from "./xcode"; import { pytestNodeId } from "./pytest"; @@ -73,16 +75,37 @@ function dotnetArgs(base: string[], filter: string): string[] { return [...dropFlag(before, ["--filter"]), "--filter", filter, ...(after ? ["--", ...after] : [])]; } +/** A file as the runner's argument: Vitest looks for the text, Jest takes a pattern; a script may run either. */ +function jsFileArgs(config: RunConfig, file: string): string[] { + if (!/[()[\]{}+*?^$|]/.test(file)) return [file]; + const runner = [config.command, ...config.args].map(runnerOf).find((r) => r !== null); + if (runner === "vitest") return [file]; + return runner === "jest" ? [escapeRegExp(file)] : [file, escapeRegExp(file)]; +} + function jsArgs(config: RunConfig, paths: string[][]): string[] | null { const base = config.args; const files = unique(paths.map((p) => p[0]!).filter(Boolean)); - const names = unique(paths.filter((p) => p.length > 1).map((p) => p.slice(1).join(" "))); + const project = vitestProject(paths[0]!); + // The runners match suites and test joined by a space. A title with the reporters' own separator + // may have been split at it (`js.ts`): the separator is optional between names. + const pattern = (names: string[]) => names.map(escapeRegExp).join(" (?:[>\\u203a] )?"); + const names = unique( + paths + .map((p) => p.slice(project === null ? 1 : 2)) + .filter((p) => p.length) + .map(pattern), + ); if (!files.length) return null; const { before, after } = splitDashDash(base); - const flags = ["-t", "--testNamePattern"]; + const flags = ["-t", "--testNamePattern", ...(project === null ? [] : ["--project"])]; const args = after === null ? dropFlag(before, flags) : [...before, "--", ...dropFlag(after, flags)]; - const filter = names.length ? ["-t", `^(?:${names.map(escapeRegExp).join("|")})$`] : []; - return appendScriptArgs(config.command, args, [...files, ...filter]); + const filter = names.length ? ["-t", `^(?:${names.join("|")})$`] : []; + return appendScriptArgs(config.command, args, [ + ...files.flatMap((f) => jsFileArgs(config, f)), + ...filter, + ...(project === null ? [] : ["--project", project]), + ]); } /** @@ -192,8 +215,8 @@ export function rerunFailedConfigs(config: RunConfig, paths: string[][]): RunCon } /** - * Go filters apply to every package of an invocation, Cargo's to every test binary, Playwright's to - * every project: each keeps its own selection. + * Go filters apply to every package of an invocation, Cargo's to every test binary, Playwright's and + * Vitest's to every project: each keeps its own selection. */ export function testsConfigs(config: RunConfig, paths: string[][], name: string): RunConfig[] | Promise { if (!paths.length) return []; @@ -207,6 +230,7 @@ export function testsConfigs(config: RunConfig, paths: string[][], name: string) const keyOf = (path: string[]) => { if (framework === "go") return path[0] ?? ""; if (framework === "cargo") return cargoRunOf(config.args, path); + if (framework === "js") return vitestProject(path) ?? ""; return framework === "playwright" ? (playwrightProject(path) ?? "") : ""; }; for (const path of paths) { diff --git a/src/features/run/testing/snapshots.test.ts b/src/features/run/testing/snapshots.test.ts index 81aa3918de..755e17604b 100644 --- a/src/features/run/testing/snapshots.test.ts +++ b/src/features/run/testing/snapshots.test.ts @@ -77,7 +77,7 @@ describe("snapshot update runs", () => { const [c, ...rest] = snapshotTestConfigs(cfg("npm", ["run", "test", "--", "-t", "old"]), paths, "file snap"); expect(rest).toEqual([]); expect(c!.name).toBe("file snap"); - expect(c!.args).toEqual(["run", "test", "--", "src/a.test.ts", "-t", "^(?:cart file snap)$"]); + expect(c!.args).toEqual(["run", "test", "--", "src/a.test.ts", "-t", "^(?:cart (?:[>\\u203a] )?file snap)$"]); const [file] = snapshotTestConfigs(cfg("npx", ["vitest", "run"]), [["src/a.test.ts"]], "a.test.ts"); expect(file!.args).toEqual(["vitest", "run", "src/a.test.ts"]); const watched: RunConfig & { watch?: boolean } = { ...cfg("npm", ["run", "test"]), watch: true }; diff --git a/src/features/run/testing/watch.ts b/src/features/run/testing/watch.ts index 0bb0f63f08..605faca662 100644 --- a/src/features/run/testing/watch.ts +++ b/src/features/run/testing/watch.ts @@ -15,7 +15,7 @@ const WATCH_FLAG: Record = { jest: "--watchAll", vitest: "--watc const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"]; const CHAIN = new Set(["&&", "||", ";", "|"]); -function runnerOf(token: string): Runner | null { +export function runnerOf(token: string): Runner | null { const name = commandName(token).replace(/\.[cm]?js$/, ""); return name === "jest" || name === "vitest" ? name : null; } diff --git a/src/features/run/updateSnapshots.test.ts b/src/features/run/updateSnapshots.test.ts index 39282a9050..80f7ad6e50 100644 --- a/src/features/run/updateSnapshots.test.ts +++ b/src/features/run/updateSnapshots.test.ts @@ -87,13 +87,13 @@ it("launches the chosen snapshot mismatches with -u, and the tab's Rerun runs th "--", "a.test.ts", "-t", - "^(?:cart total)$", + "^(?:cart (?:[>\\u203a] )?total)$", "-u", "--testPathIgnorePatterns", "^(?!.*(?:^|[\\\\/])(?:a\\.test\\.ts)$)", ]); await vi.waitFor(() => expect(session(id).config.args).not.toContain("-u")); - expect(session(id).config.args).toEqual(["run", "test", "--", "a.test.ts", "-t", "^(?:cart total)$"]); + expect(session(id).config.args).toEqual(["run", "test", "--", "a.test.ts", "-t", "^(?:cart (?:[>\\u203a] )?total)$"]); expect(session(id).config.name).toBe("total"); expect(session(id).baseConfig).toEqual(base); expect(rerunConfig(session(id)).args).not.toContain("-u");