From 7413a08ee6dcce51c026a844de8b13167502dbf3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 13:45:22 +0000 Subject: [PATCH 1/6] bun:test: support the tagged-template table form of .each test.each`...`, it.each`...` and describe.each`...` call each(strings, ...values). fn_each read the first argument only, so the strings array became the table: one test per string segment, no values, and the title was not interpolated. fn_each now builds one row object per row when it gets a template strings array and values. The headings come from strings[0] with jest-each's grammar. The rows go in the existing table slot, so the title call runs the array-of-objects path. A malformed table does not throw from .each: the title call throws the error, with jest-each's wording. is_js_whitespace moves from node_assert.rs to bun_core::strings, and both users share it. --- docs/test/writing-tests.mdx | 36 +++ packages/bun-types/test.d.ts | 52 +++++ src/bun_core/string/immutable.rs | 7 + src/runtime/node/node_assert.rs | 22 +- src/runtime/test_runner/ScopeFunctions.rs | 194 +++++++++++++++- test/cli/test/bun-test.test.ts | 113 +++++++++ test/integration/bun-types/fixture/test.ts | 43 ++++ test/js/bun/test/jest-each-gc-root.test.ts | 114 +++++++++ test/js/bun/test/jest-each.test.ts | 257 +++++++++++++++++++++ 9 files changed, 813 insertions(+), 25 deletions(-) diff --git a/docs/test/writing-tests.mdx b/docs/test/writing-tests.mdx index 02e117455330..7ef187559256 100644 --- a/docs/test/writing-tests.mdx +++ b/docs/test/writing-tests.mdx @@ -345,6 +345,42 @@ test.each([ }); ``` +### Tagged Template Tables + +You can write the table as a tagged template literal. The first line has the column names, separated by `|`. Each line after it has one `${value}` for each column. Bun passes each row to your test function as one object, with the column names as its keys. + +```ts title="example.test.ts" icon="/icons/typescript.svg" +test.each` + a | b | expected + ${1} | ${2} | ${3} + ${4} | ${5} | ${9} +`("add($a, $b) = $expected", ({ a, b, expected }) => { + expect(a + b).toBe(expected); +}); +``` + +`describe.each` accepts the same form. In the title, `$a` prints the value of column `a`, the same as for a table of objects. + +Put the column names on their own line after the opening backtick. A column name has no spaces in it. Bun reads the `|` separators on that line only, and takes the values in the order they appear. + +In TypeScript, pass the type of a row as the type argument: + +```ts title="example.test.ts" icon="/icons/typescript.svg" +test.each<{ input: string; length: number }>` + input | length + ${"bun"} | ${3} + ${"bagel"} | ${5} +`("$input has $length characters", ({ input, length }) => { + expect(input.length).toBe(length); +}); +``` + +Bun builds the row objects once, when `.each` runs. The call that passes the title throws an error if the table is malformed: + +- the template has no `${value}` +- the number of values is not a multiple of the number of columns +- the first line is not a row of column names + ### Format Specifiers Use these specifiers to format the test title: diff --git a/packages/bun-types/test.d.ts b/packages/bun-types/test.d.ts index 2ce1cba4695b..cda1e953ab03 100644 --- a/packages/bun-types/test.d.ts +++ b/packages/bun-types/test.d.ts @@ -273,6 +273,35 @@ declare module "bun:test" { * @param condition if these tests should be marked TODO */ todoIf(condition: boolean): Describe; + /** + * Returns a function that runs for each row of a table written as a tagged template literal. + * + * The first line of the template has the column names, separated by `|`. + * Each line after it has one `${value}` for each column. + * The describe fn gets each row as one object, with the column names as its keys. + * To type that object, pass it as the type argument: `describe.each<{ a: number }>`. + * + * A table with no `${value}`, or with a row that has too few, throws when + * the returned function is called. + * + * @example + * ```ts + * describe.each` + * a | b | expected + * ${1} | ${2} | ${3} + * ${4} | ${5} | ${9} + * `("add($a, $b)", ({ a, b, expected }) => { + * test(`returns ${expected}`, () => { + * expect(a + b).toBe(expected); + * }); + * }); + * ``` + */ + each>( + strings: TemplateStringsArray, + value: unknown, + ...values: unknown[] + ): Describe<[Row]>; /** * Returns a function that runs for each item in `table`. * @@ -569,6 +598,29 @@ declare module "bun:test" { * @param condition if the test should run serially */ serialIf(condition: boolean): Test; + /** + * Returns a function that runs for each row of a table written as a tagged template literal. + * + * The first line of the template has the column names, separated by `|`. + * Each line after it has one `${value}` for each column. + * The test fn gets each row as one object, with the column names as its keys. + * To type that object, pass it as the type argument: `test.each<{ a: number }>`. + * + * A table with no `${value}`, or with a row that has too few, throws when + * the returned function is called. + * + * @example + * ```ts + * test.each` + * a | b | expected + * ${1} | ${2} | ${3} + * ${4} | ${5} | ${9} + * `("add($a, $b) = $expected", ({ a, b, expected }) => { + * expect(a + b).toBe(expected); + * }); + * ``` + */ + each>(strings: TemplateStringsArray, value: unknown, ...values: unknown[]): Test<[Row]>; /** * Returns a function that runs for each item in `table`. * diff --git a/src/bun_core/string/immutable.rs b/src/bun_core/string/immutable.rs index f5b37f380d78..8f169adc76d8 100644 --- a/src/bun_core/string/immutable.rs +++ b/src/bun_core/string/immutable.rs @@ -2239,6 +2239,13 @@ pub const fn is_unicode_space_separator(cp: u32) -> bool { ) } +/// ECMAScript `WhiteSpace` or `LineTerminator`: the RegExp `\s` class, and +/// the set `String.prototype.trim` strips. +#[inline] +pub const fn is_js_whitespace(cp: u32) -> bool { + matches!(cp, 0x09..=0x0D | 0x2028 | 0x2029 | 0xFEFF) || is_unicode_space_separator(cp) +} + /// SIMD-accelerated iterator that yields slices of text between ANSI escape sequences. /// The C++ side uses ANSI::findEscapeCharacter (SIMD) and ANSI::consumeANSI. #[repr(C)] diff --git a/src/runtime/node/node_assert.rs b/src/runtime/node/node_assert.rs index 264f991dd537..6e5bbb9379f3 100644 --- a/src/runtime/node/node_assert.rs +++ b/src/runtime/node/node_assert.rs @@ -1,5 +1,5 @@ use bun_core::String as BunString; -use bun_core::strings::EncodingNonAscii; +use bun_core::strings::{self, EncodingNonAscii}; use bun_jsc::js_object::PojoFields; use bun_jsc::{FromAny, JSGlobalObject, JSObject, JSValue, JsError, JsResult, StringJsc}; @@ -203,24 +203,6 @@ fn append_ascii(out: &mut Vec, bytes: &[u8]) { out.extend(bytes.iter().map(|&b| C::from(b))); } -/// `String.prototype.trimEnd` whitespace set (WhiteSpace + LineTerminator). -fn is_js_whitespace(c: u32) -> bool { - matches!( - c, - 0x09..=0x0D - | 0x20 - | 0xA0 - | 0x1680 - | 0x2000..=0x200A - | 0x2028 - | 0x2029 - | 0x202F - | 0x205F - | 0x3000 - | 0xFEFF - ) -} - fn emit( global: &JSGlobalObject, diff_list: &MyersDiff::DiffList, @@ -341,7 +323,7 @@ fn render_lines>(diff: &[Diff], colors: &Colors) } // `message.trimEnd()` (the leading "\n" is prepended after trimming in JS, so keep it). - while out.len() > 1 && is_js_whitespace(out[out.len() - 1].as_u32()) { + while out.len() > 1 && strings::is_js_whitespace(out[out.len() - 1].as_u32()) { out.pop(); } (out, skipped) diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index 87a6b77acdda..4c7e60a5acba 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -2,7 +2,7 @@ use core::fmt; use crate::test_runner::expect::JSValueTestExt; use bun_jsc::{CallFrame, JSGlobalObject, JSValue, JsClass, JsResult}; -use bun_core::String as BunString; +use bun_core::{strings, EncodedSlice, String as BunString}; use crate::test_runner::bun_test::{self, BaseScopeCfg, BunTest, DescribeScope}; use crate::test_runner::bun_test::js_fns::Signature; @@ -58,9 +58,11 @@ pub enum Mode { pub(crate) struct ScopeFunctions { pub(crate) mode: Mode, pub(crate) cfg: BaseScopeCfg, - /// typically `.zero`. not Strong.Optional because codegen visits the C++ `m_each` - /// WriteBarrier on the JS wrapper (see `values: ["each"]` in jest.classes.ts). This - /// field is kept in sync with that slot via `js::each_set_cached` in `create_unbound`. + /// typically `.zero`. After `.each`: the table array, or the Error of a malformed + /// template table, which the title call throws. not Strong.Optional because codegen + /// visits the C++ `m_each` WriteBarrier on the JS wrapper (see `values: ["each"]` in + /// jest.classes.ts). This field is kept in sync with that slot via + /// `js::each_set_cached` in `create_unbound`. pub(crate) each: JSValue, } @@ -117,7 +119,8 @@ impl ScopeFunctions { pub(crate) fn fn_each(this: &Self, global: &JSGlobalObject, frame: &CallFrame) -> JsResult { let _g = group_log::begin(); - let [array] = frame.arguments_as_array::<1>(); + let args = frame.arguments(); + let array = args.first().copied().unwrap_or(JSValue::UNDEFINED); if array.is_undefined_or_null() || !array.is_array() { let mut formatter = bun_jsc::ConsoleObject::Formatter::new(global); return Err(global.throw(format_args!("Expected array, got {}", array.to_fmt(&mut formatter)))); @@ -126,10 +129,185 @@ impl ScopeFunctions { if !this.each.is_empty() { return Err(global.throw(format_args!("Cannot {} on {}", "each", this))); } + // test.each`a | b \n ${1} | ${2}` calls each(strings, 1, 2). + if args.len() > 1 && is_template_strings(global, array)? { + return bun_jsc::MarkedArgumentBuffer::new(|rooted| { + let table = template_table(global, rooted, array, &args[1..])?; + create_bound(global, this.mode, table, this.cfg, "each") + }); + } create_bound(global, this.mode, array, this.cfg, "each") } } +/// A tagged template passes its tag an array of strings that has an own `raw` array. +fn is_template_strings(global: &JSGlobalObject, array: JSValue) -> JsResult { + Ok(array.get_own_truthy(global, "raw")?.is_some_and(|raw| raw.is_array())) +} + +/// jest-each's grammar for the heading row, `/^\n\s*[^\s]+\s*(\|\s*[^\s]+\s*)*\n/`: +/// the end of its match in `header`. +/// +/// A word is a run of characters that are not whitespace. A backtracking matcher +/// leaves a word in one of two states: the word ended a heading, or its last +/// character was the `|` between two headings. The scan goes from the last word to +/// the first and keeps where the match ends from each state. It tries the states +/// in the matcher's order, so it finds the same end with no backtracking. +fn match_template_headings(header: EncodedSlice<'_>) -> Option { + let is_space = |i: usize| strings::is_js_whitespace(u32::from(header.char_at(i))); + if header.len == 0 || header.char_at(0) != u16::from(b'\n') { + return None; + } + // Where the match ends when the word at `i` comes after a heading, or after a `|`. + let (mut from_heading, mut from_pipe): (Option, Option) = (None, None); + let mut i = header.len; + loop { + let mut newline_end = None; + while i > 1 && is_space(i - 1) { + if newline_end.is_none() && header.char_at(i - 1) == u16::from(b'\n') { + newline_end = Some(i); + } + i -= 1; + } + if i <= 1 { + return from_pipe; + } + let word_end = i; + while i > 1 && !is_space(i - 1) { + i -= 1; + } + let word_len = word_end - i; + let ends_with_pipe = header.char_at(word_end - 1) == u16::from(b'|'); + // The last `len` characters of the word start with a heading. The heading takes all + // of them: then a `|` word follows, or the match stops at the last newline after the + // word. If that fails, the heading stops before a `|` that ends the word. + let heading_then = |len: usize| { + from_heading.or(newline_end).or(if ends_with_pipe && len >= 2 { from_pipe } else { None }) + }; + (from_heading, from_pipe) = ( + if header.char_at(i) != u16::from(b'|') { + None + } else if word_len == 1 { + from_pipe + } else { + heading_then(word_len - 1) + }, + heading_then(word_len), + ); + } +} + +/// `header[..end]` without its whitespace, split on `|`. +fn template_headings(header: EncodedSlice<'_>, end: usize) -> Vec { + let mut headings = Vec::new(); + let mut heading: Vec = Vec::new(); + for i in 0..end { + let unit = header.char_at(i); + if unit == u16::from(b'|') { + headings.push(BunString::clone_utf16(&heading)); + heading.clear(); + } else if !strings::is_js_whitespace(u32::from(unit)) { + heading.push(unit); + } + } + headings.push(BunString::clone_utf16(&heading)); + headings +} + +/// The table for `each(strings, ...values)`: one object per row, keyed by the headings in +/// `strings[0]`. A malformed table gives the Error that the title call throws, in +/// jest-each's wording. `rooted` keeps the result alive until the caller stores it. +fn template_table( + global: &JSGlobalObject, + rooted: &mut bun_jsc::MarkedArgumentBuffer, + template_strings: JSValue, + values: &[JSValue], +) -> JsResult { + let table_error = |rooted: &mut bun_jsc::MarkedArgumentBuffer, message: fmt::Arguments<'_>| { + let error = global.create_error_instance(message); + if error.is_empty() { + return Err(bun_jsc::JsError::Thrown); + } + rooted.append(error); + Ok(error) + }; + + let first = template_strings.get_index(global, 0)?; + rooted.append(first); + let headings = if first.is_string() { + let header = first.to_bun_string(global)?; + let header = header.to_encoded_slice(); + match_template_headings(header).map(|end| template_headings(header, end)) + } else { + None + }; + let Some(headings) = headings else { + let mut formatter = crate::test_runner::expect::make_formatter(global); + return table_error( + rooted, + format_args!( + "Table headings do not conform to expected format:\n\nheading1 | headingN\n\nReceived:\n\n{}", + first.to_fmt(&mut formatter) + ), + ); + }; + + let incomplete = values.len() % headings.len(); + if incomplete != 0 { + let mut heading_list: Vec = Vec::new(); + for (i, heading) in headings.iter().enumerate() { + if i != 0 { + heading_list.extend_from_slice(b" | "); + } + heading_list.extend_from_slice(heading.to_utf8().slice()); + } + let received = JSValue::create_array_from_slice(global, values)?; + rooted.append(received); + let missing = headings.len() - incomplete; + let mut formatter = crate::test_runner::expect::make_formatter(global); + return table_error( + rooted, + format_args!( + "Not enough arguments supplied for given headings:\n{}\n\nReceived:\n{}\n\nMissing {} argument{}", + bstr::BStr::new(&heading_list), + received.to_fmt(&mut formatter), + missing, + if missing == 1 { "" } else { "s" }, + ), + ); + } + + let rows = JSValue::create_empty_array(global, values.len() / headings.len())?; + rooted.append(rows); + for (row_index, row_values) in values.chunks_exact(headings.len()).enumerate() { + let row = JSValue::create_empty_object(global, headings.len()); + rows.put_index(global, row_index as u32, row)?; + for (heading, value) in headings.iter().zip(row_values) { + row.put_may_be_index(global, heading, *value)?; + } + } + Ok(rows) +} + +/// A template with no `${}` calls `each(strings)`, so `.each` kept `strings` as a table of one row. +/// That row is the text of the template, or undefined when the text has an invalid escape. +fn reject_template_without_values(global: &JSGlobalObject, table: JSValue) -> JsResult<()> { + let first = table.get_index(global, 0)?; + if !(first.is_string() || first.is_undefined()) || !is_template_strings(global, table)? { + return Ok(()); + } + if first.is_string() { + let text = first.to_bun_string(global)?; + let text = text.to_encoded_slice(); + if (0..text.len).all(|i| strings::is_js_whitespace(u32::from(text.char_at(i)))) { + return Err(global.throw(format_args!("`.each` called with an empty Tagged Template Literal of table data."))); + } + } + Err(global.throw(format_args!( + "`.each` called with a Tagged Template Literal with no data, remember to interpolate with ${{expression}} syntax." + ))) +} + #[bun_jsc::host_fn] fn call_as_function(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { let _g = group_log::begin(); @@ -168,10 +346,16 @@ fn call_as_function(global: &JSGlobalObject, frame: &CallFrame) -> JsResult { expect(stderr).toContain("1 | $missing| $a.b.c| 1"); }); }); + + describe.concurrent("tagged template table", () => { + // Runs one test file. `results` has the line of each test, without the duration. + async function run(contents: string, ...args: string[]) { + using dir = tempDir("bun-test-each-template", { "table.test.ts": contents }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "./table.test.ts", ...args], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const results = stderr + .split(/\r?\n/) + .filter(line => /^\((pass|fail|skip|todo)\) /.test(line)) + .map(line => line.replace(/ \[[\d.]+m?s\]$/, "")); + return { results, stderr: stderr.replaceAll("\r\n", "\n"), exitCode }; + } + + // The first table is from https://github.com/oven-sh/bun/issues/6364. The rows of the second one have to fail. + const tables = ` + import { test, expect } from "bun:test"; + test.each\` + a | b | expected + \${1} | \${2} | \${3} + \${2} | \${2} | \${4} + \`("$a and $b add up to $expected", ({ a, b, expected }) => { + expect(a + b).toBe(expected); + }); + const price = { apple: 3, pear: 4 }; + test.each\` + fruit | expected + \${"apple"} | \${999} + \${"pear"} | \${999} + \`("price of $fruit is $expected", ({ fruit, expected }) => { + expect(price[fruit]).toBe(expected); + }); + `; + + test("runs one test for each row, with the values of the row in the title", async () => { + const { results, exitCode } = await run(tables); + expect({ results, exitCode }).toEqual({ + results: [ + "(pass) 1 and 2 add up to 3", + "(pass) 2 and 2 add up to 4", + "(fail) price of apple is 999", + "(fail) price of pear is 999", + ], + exitCode: 1, + }); + }); + + test("matches -t against the title of each row", async () => { + const { results, exitCode } = await run(tables, "-t", "2 and 2|of pear"); + expect({ results, exitCode }).toEqual({ + results: ["(pass) 2 and 2 add up to 4", "(fail) price of pear is 999"], + exitCode: 1, + }); + }); + + const noValues = + "`.each` called with a Tagged Template Literal with no data, remember to interpolate with ${expression} syntax."; + test.each([ + ["headings and no values", "test.each`\n a | b\n`", [], noValues], + ["no text", "test.each``", [], "`.each` called with an empty Tagged Template Literal of table data."], + ["an invalid escape and no values", "test.each`\\unicode`", [], noValues], + [ + "values that do not fill the last row", + "test.each`\n a | b\n ${1} | ${2}\n ${3}\n`", + [], + "Not enough arguments supplied for given headings:\na | b\n\nReceived:\n[ 1, 2, 3 ]\n\nMissing 1 argument", + ], + [ + "headings on the line of the backtick", + "test.each`a | b\n ${1} | ${2}\n`", + [], + 'Table headings do not conform to expected format:\n\nheading1 | headingN\n\nReceived:\n\n"a | b\\n "', + ], + ["test.skip.each", "test.skip.each`\n a | b\n`", [], noValues], + ["test.todo.each", "test.todo.each`\n a | b\n`", [], noValues], + ["test.failing.each", "test.failing.each`\n a | b\n`", [], noValues], + ["describe.each", "describe.each`\n a | b\n`", [], noValues], + ["a modifier after .each", "test.each`\n a | b\n`.skip", [], noValues], + ["a title that -t filters out", "test.each`\n a | b\n`", ["-t", "sentinel"], noValues], + ])("fails the file for a malformed table: %s", async (_, each, args, message) => { + const { results, stderr, exitCode } = await run( + ` + import { test, describe } from "bun:test"; + ${each}("row $a", () => {}); + test("sentinel", () => {}); + `, + ...args, + ); + expect(stderr).toContain(`error: ${message}\n`); + expect({ rows: results.filter(line => line.includes("row")), exitCode }).toEqual({ rows: [], exitCode: 1 }); + }); + + test("a malformed table that gets no title does not fail the file", async () => { + const { results, exitCode } = await run(` + import { test } from "bun:test"; + test.each\` + a | b + \`; + test.each\` + a | b + \${1} + \`; + test("sentinel", () => {}); + `); + expect({ results, exitCode }).toEqual({ results: ["(pass) sentinel"], exitCode: 0 }); + }); + }); }); test("Prints error when no test matches", () => { diff --git a/test/integration/bun-types/fixture/test.ts b/test/integration/bun-types/fixture/test.ts index 8725d1db569a..bd91e2a63992 100644 --- a/test/integration/bun-types/fixture/test.ts +++ b/test/integration/bun-types/fixture/test.ts @@ -391,6 +391,49 @@ test.each(mylist)("test.each", (a, done) => { expectType<(err?: unknown) => void>(done); }); +// tagged template table: one row object per test +test.each` + a | b | expected + ${1} | ${2} | ${3} +`("test.each", (row, done) => { + expectType(row).is>(); + expectType(done).is<(err?: unknown) => void>(); +}); +test.each<{ a: number; b: string }>` + a | b + ${1} | ${"x"} +`("test.each", ({ a, b }) => { + expectType(a).is(); + expectType(b).is(); +}); +describe.each<{ a: number }>` + a + ${1} +`("describe.each", row => { + expectType(row).is<{ a: number }>(); +}); +test.skip.each` + a + ${1} +`.todo("test.each", row => { + expectType(row).is>(); +}); +describe.each` + a + ${1} +`("describe.each", row => { + expectType(row).is>(); +}); +// a table needs at least one ${value} +// @ts-expect-error +test.each` + a | b +`("test.each", () => {}); +// @ts-expect-error +describe.each` + a | b +`("describe.each", () => {}); + // Advanced use case tests for #18511: // 1. => When assignable to, we should pass (e.g. new Set() is assignable to Set). diff --git a/test/js/bun/test/jest-each-gc-root.test.ts b/test/js/bun/test/jest-each-gc-root.test.ts index ecfe6d6cb93d..73791225fbae 100644 --- a/test/js/bun/test/jest-each-gc-root.test.ts +++ b/test/js/bun/test/jest-each-gc-root.test.ts @@ -113,3 +113,117 @@ test("test.each/describe.each table array is a GC root", async () => { expect(stdout + stderr).not.toContain("Expected array"); expect(exitCode).toBe(0); }, 60_000); + +async function runFixture(fixture: string, env: Record) { + using dir = tempDir("jest-each-gc-template", { + "each-gc.test.ts": fixture, + }); + + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "each-gc.test.ts"], + env: { ...bunEnv, ...env }, + cwd: String(dir), + stderr: "pipe", + stdout: "pipe", + }); + + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + return { stderr, exitCode }; +} + +// .each builds the rows of a template table. After it returns, the ScopeFunctions is +// the only owner of the rows, and the rows are the only owners of the values. +const templateFixture = ` +import { test, describe, expect } from "bun:test"; + +const seen: unknown[][] = []; + +const templateEach = (() => (() => + test.each\` + name | payload + \${"alpha"} | \${{ list: [1, 2] }} + \${"beta"} | \${{ list: [3, 4] }} + \` +)())(); + +const chainedTemplateEach = (() => (() => + describe.each\` + name | payload + \${"gamma"} | \${{ list: [5, 6] }} + \`.skipIf(false) +)())(); + +Bun.gc(true); + +templateEach("template.each $name", ({ name, payload }) => { + seen.push([name, ...payload.list]); +}); + +Bun.gc(true); + +chainedTemplateEach("chained template.each $name", ({ name, payload }) => { + test("inner", () => { + seen.push([name, ...payload.list]); + }); +}); + +test("all rows survived GC", () => { + expect(seen).toEqual([ + ["alpha", 1, 2], + ["beta", 3, 4], + ["gamma", 5, 6], + ]); +}); +`; + +test("the rows of a test.each/describe.each template table are a GC root", async () => { + const gcEnv: Record = { BUN_JSC_useZombieMode: "1" }; + if (!isWindows) gcEnv.BUN_JSC_collectContinuously = "1"; + + const { stderr, exitCode } = await runFixture(templateFixture, gcEnv); + + expect(stderr).toContain(" 4 pass"); + expect(stderr).toContain(" 0 fail"); + expect(exitCode).toBe(0); +}, 60_000); + +// A collection runs while .each builds the rows, and while it makes the function that keeps +// them: the row array and its rows have no other owner then. slowPathAllocsBetweenGCs +// collects at every Nth slow allocation, so a table of 800 rows gets collections in both. +const buildFixture = ` +import { test, describe, expect } from "bun:test"; + +const ROWS = 800; +const strings = Object.assign(["\\n index | payload\\n", ...Array(ROWS * 2).fill(" ")], { raw: [] }); +const rows = (() => (() => { + const values = []; + for (let i = 0; i < ROWS; i++) values.push(i, { list: [i, i + 1] }); + return describe.each(strings, ...values); +})())(); + +Bun.gc(true); + +let sum = 0; +rows("row $index", ({ index, payload }) => { + if (payload.list[0] === index && payload.list[1] === index + 1) sum += index; +}); + +test("every row survived", () => { + expect(sum).toBe((ROWS * (ROWS - 1)) / 2); +}); +`; + +test.concurrent.each([3, 4])( + "a template table survives a GC while .each builds its rows (every %i slow allocations)", + async period => { + const { stderr, exitCode } = await runFixture(buildFixture, { + BUN_JSC_useZombieMode: "1", + BUN_JSC_slowPathAllocsBetweenGCs: String(period), + }); + + expect(stderr).toContain(" 1 pass"); + expect(stderr).toContain(" 0 fail"); + expect(exitCode).toBe(0); + }, + 60_000, +); diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index 0bd0239ac72a..87f1f99683e2 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -57,3 +57,260 @@ describe.each(["some", "cool", "strings"])("works with describe: %s", s => { describe("does not return zero", () => { expect(it.each([1, 2])("wat", () => {})).toBeUndefined(); }); + +describe("tagged template table", () => { + it.each` + a | b | expected + ${1} | ${2} | ${3} + ${"x"} | ${"y"} | ${"xy"} + `("$a + $b = $expected", function (row) { + expect(arguments.length).toBe(1); + expect(Reflect.ownKeys(row)).toEqual(["a", "b", "expected"]); + expect(row.a + row.b).toBe(row.expected); + }); + + it.each` + a | b | expected + ${1} | ${2} | ${3} + `("passes done after the row", (row, done) => { + expect(row).toStrictEqual({ a: 1, b: 2, expected: 3 }); + expect(done).toBeTypeOf("function"); + done(); + }); + + const object = { id: 1 }; + it.each` + object | nothing | missing | zero | no | empty + ${object} | ${null} | ${undefined} | ${0} | ${false} | ${""} + `("passes each value through untouched", row => { + expect(Reflect.ownKeys(row)).toEqual(["object", "nothing", "missing", "zero", "no", "empty"]); + expect(row.object).toBe(object); + expect(row).toStrictEqual({ object, nothing: null, missing: undefined, zero: 0, no: false, empty: "" }); + }); + + it.each` + café | 名前 | 😀 + ${"one"} | ${"Alice"} | ${42} + `("keeps headings that are not ASCII", row => { + expect(Reflect.ownKeys(row)).toEqual(["café", "名前", "😀"]); + expect(row).toStrictEqual({ café: "one", 名前: "Alice", "😀": 42 }); + }); + + it.each` + 0 | __proto__ | b | b + ${"zero"} | ${"proto"} | ${"old"} | ${"new"} + `("makes an own data property for an index, __proto__ and a repeated heading", row => { + const property = (value: string) => ({ value, writable: true, enumerable: true, configurable: true }); + expect(Object.getPrototypeOf(row)).toBe(Object.prototype); + expect(Object.entries(Object.getOwnPropertyDescriptors(row))).toEqual([ + ["0", property("zero")], + ["__proto__", property("proto")], + ["b", property("new")], + ]); + }); + + describe.each` + n | square + ${2} | ${4} + ${3} | ${9} + `("describe.each: $n", function (row) { + const argumentCount = arguments.length; + it(`squares to ${row.square}`, () => { + expect(argumentCount).toBe(1); + expect(row.n * row.n).toBe(row.square); + }); + }); + + it.if(true).each` + a + ${1} + `("a modifier before .each", row => { + expect(row).toStrictEqual({ a: 1 }); + }); + + it.each` + a + ${1} + `.skipIf(false)("a modifier after .each", row => { + expect(row).toStrictEqual({ a: 1 }); + }); + + it.skip.each` + a + ${1} + `("skip before .each", () => { + throw new Error("a skipped row ran"); + }); + + // Prettier aligns a table that has `it.each` as its tag. This tag keeps the table as written. + const eachOf = (strings: TemplateStringsArray, first: unknown, ...rest: unknown[]) => + it.each(strings, first, ...rest); + eachOf` + + a|b + + ${1} ${2} + ${3} + ${4} + `("reads the headings from their line and takes the values in order", row => { + expect(Reflect.ownKeys(row)).toEqual(["a", "b"]); + expect(row.b - row.a).toBe(1); + }); + + // @ts-expect-error an array table takes one argument + it.each([[1, 2]], "ignored")("an array with more arguments after it is an array table: %d %d", (a, b) => { + expect([a, b]).toEqual([1, 2]); + }); + + // A tag gets (strings, ...values), and `strings` has an own `raw`. + const strings = (...cooked: string[]) => + Object.assign(cooked, { raw: [...cooked] }) as unknown as TemplateStringsArray; + + it.each( + strings("\n a||\ud83d\n", "", "", ""), + 1, + 2, + 3, + )("keeps a heading that is empty or half of a pair", row => { + expect(Object.entries(row)).toEqual([ + ["a", 1], + ["", 2], + ["\ud83d", 3], + ]); + }); + + describe("malformed", () => { + // `.each` keeps the error of a malformed table. The call with the title throws it. + const titleCallError = (each: (title: string, fn: () => void) => unknown) => { + try { + each("title", () => {}); + } catch (error) { + return (error as Error).message; + } + }; + const noValues = + "`.each` called with a Tagged Template Literal with no data, remember to interpolate with ${expression} syntax."; + const noText = "`.each` called with an empty Tagged Template Literal of table data."; + const badHeadings = (received: string) => + `Table headings do not conform to expected format:\n\nheading1 | headingN\n\nReceived:\n\n${received}`; + + it("headings and no values", () => { + // @ts-expect-error a table needs a value + const each = it.each` + a | b + `; + expect(titleCallError(each)).toBe(noValues); + // @ts-expect-error + const invalidEscape = describe.each` + \unicode + `; + expect(titleCallError(invalidEscape)).toBe(noValues); + }); + + it("no text", () => { + // @ts-expect-error + const empty = it.each``; + expect(titleCallError(empty)).toBe(noText); + expect(titleCallError((it.each as any)(strings(" \n\t\u00a0\u2028\ufeff")))).toBe(noText); + }); + + it("values that do not fill the last row", () => { + const each = it.each` + a | b + ${1} | ${2} + ${3} + `; + const message = + "Not enough arguments supplied for given headings:\na | b\n\nReceived:\n[ 1, 2, 3 ]\n\nMissing 1 argument"; + expect(titleCallError(each)).toBe(message); + expect(titleCallError(each.skip)).toBe(message); + expect(titleCallError(each.skipIf(false))).toBe(message); + expect( + titleCallError(describe.each` + café | b | c + ${"x"} + `), + ).toBe( + 'Not enough arguments supplied for given headings:\ncafé | b | c\n\nReceived:\n[ "x" ]\n\nMissing 2 arguments', + ); + }); + + it("headings that are not a line of their own", () => { + expect(titleCallError(it.each(strings("a | b\n", ""), 1))).toBe(badHeadings('"a | b\\n"')); + expect(titleCallError(it.each(strings("\n a | b", ""), 1))).toBe(badHeadings('"\\n a | b"')); + expect( + titleCallError( + it.each` + \unicode + ${1} + `, + ), + ).toBe(badHeadings("undefined")); + }); + + it("a heading that is empty or has a space in it", () => { + for (const header of ["\n a b | c\n", "\n | a\n", "\n a |\n", "\n a || b\n", "\n \n"]) { + expect(titleCallError(it.each(strings(header, ""), 1))).toBe(badHeadings(JSON.stringify(header))); + } + }); + }); + + describe("heading grammar", () => { + // jest-each's, from its src/validation.ts and src/bind.ts. + const HEADINGS = /^\n\s*[^\s]+\s*(\|\s*[^\s]+\s*)*\n/; + const jestHeadings = (header: string) => header.match(HEADINGS)?.[0].replace(/\s/g, "").split("|"); + + const headers = new Set(); + const add = (prefix: string, depth: number) => { + headers.add("\n" + prefix); + if (depth < 4) for (const next of ["\n", " ", "a", "|"]) add(prefix + next, depth + 1); + }; + add("", 0); + for (const header of [ + "", + " a\n", + "\n first | second | third\n ", + "\n\ta\t|\tb\t\n", + "\n a | b\r\n", + "\n a\u00a0|\u3000b \n", + "\n a\u2028| b\n", + "\n\ufeffa |\n b\n", + "\n a|\n b\n", + "\n a |b| c\n d | e\n", + "\n a\u200b | b\n", + "\n 😀 | é\n", + "\n \ud83d \n", + ]) { + headers.add(header); + } + + const mismatches: unknown[] = []; + let accepted = 0; + for (const header of headers) { + const expected = jestHeadings(header); + // One value more than a row takes: the error lists the headings. A table of one column takes any count. + const values = expected && expected.length > 1 ? Array(expected.length + 1).fill(0) : [0]; + const each = (describe.each as any)(strings(header, ""), ...values); + let got: unknown; + try { + each("one heading", (row: object) => { + if (Reflect.ownKeys(row).join("|") !== expected?.join("|")) mismatches.push([header, Reflect.ownKeys(row)]); + }); + got = 1; + } catch (error) { + got = (error as Error).message.split("\n\nReceived:")[0]; + } + let want: unknown = "Table headings do not conform to expected format:\n\nheading1 | headingN"; + if (expected) { + accepted++; + want = expected.length > 1 ? "Not enough arguments supplied for given headings:\n" + expected.join(" | ") : 1; + } + if (got !== want) mismatches.push([header, got, want]); + } + + it("is the grammar of jest-each", () => { + expect(mismatches).toEqual([]); + expect({ headers: headers.size, accepted }).toEqual({ headers: 354, accepted: 137 }); + }); + }); +}); From 719a01098038f4d281b6b717e624e04430988bbc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:47:07 +0000 Subject: [PATCH 2/6] bun:test: read the headings of a template table from one row of names The heading row is one line of names with | between them. jest-each also takes an empty name, and a row that goes on after a | on the next line. Those are malformed here, with the same error. For every other table the headings are the ones jest-each reads. The row type of the template overloads defaults to any, so a callback can annotate its row parameter. --- docs/test/writing-tests.mdx | 8 +- packages/bun-types/test.d.ts | 24 +++--- src/runtime/test_runner/ScopeFunctions.rs | 93 +++++++++------------- test/integration/bun-types/fixture/test.ts | 20 ++++- test/js/bun/test/jest-each.test.ts | 56 ++++++++----- 5 files changed, 108 insertions(+), 93 deletions(-) diff --git a/docs/test/writing-tests.mdx b/docs/test/writing-tests.mdx index 7ef187559256..d477fe3fbbde 100644 --- a/docs/test/writing-tests.mdx +++ b/docs/test/writing-tests.mdx @@ -359,11 +359,11 @@ test.each` }); ``` -`describe.each` accepts the same form. In the title, `$a` prints the value of column `a`, the same as for a table of objects. +`describe.each` accepts the same form. The title takes the same `$name` placeholders as for a table of objects. -Put the column names on their own line after the opening backtick. A column name has no spaces in it. Bun reads the `|` separators on that line only, and takes the values in the order they appear. +Put the column names on one line of their own, with `|` between them. A column name has no spaces in it. Bun takes the values in the order they appear, whatever is between them. -In TypeScript, pass the type of a row as the type argument: +In TypeScript, annotate the row parameter, or pass the type of a row as the type argument: ```ts title="example.test.ts" icon="/icons/typescript.svg" test.each<{ input: string; length: number }>` @@ -379,7 +379,7 @@ Bun builds the row objects once, when `.each` runs. The call that passes the tit - the template has no `${value}` - the number of values is not a multiple of the number of columns -- the first line is not a row of column names +- the column names are not one line of names with `|` between them ### Format Specifiers diff --git a/packages/bun-types/test.d.ts b/packages/bun-types/test.d.ts index cda1e953ab03..39ff997b6085 100644 --- a/packages/bun-types/test.d.ts +++ b/packages/bun-types/test.d.ts @@ -279,10 +279,12 @@ declare module "bun:test" { * The first line of the template has the column names, separated by `|`. * Each line after it has one `${value}` for each column. * The describe fn gets each row as one object, with the column names as its keys. - * To type that object, pass it as the type argument: `describe.each<{ a: number }>`. + * To type that object, annotate the parameter or pass the type argument: + * `describe.each<{ a: number }>`. * - * A table with no `${value}`, or with a row that has too few, throws when - * the returned function is called. + * The returned function throws when the table has no `${value}`, when the + * number of values is not a multiple of the number of columns, or when the + * column names are not one line of names separated by `|`. * * @example * ```ts @@ -297,11 +299,7 @@ declare module "bun:test" { * }); * ``` */ - each>( - strings: TemplateStringsArray, - value: unknown, - ...values: unknown[] - ): Describe<[Row]>; + each(strings: TemplateStringsArray, value: unknown, ...values: unknown[]): Describe<[Row]>; /** * Returns a function that runs for each item in `table`. * @@ -604,10 +602,12 @@ declare module "bun:test" { * The first line of the template has the column names, separated by `|`. * Each line after it has one `${value}` for each column. * The test fn gets each row as one object, with the column names as its keys. - * To type that object, pass it as the type argument: `test.each<{ a: number }>`. + * To type that object, annotate the parameter or pass the type argument: + * `test.each<{ a: number }>`. * - * A table with no `${value}`, or with a row that has too few, throws when - * the returned function is called. + * The returned function throws when the table has no `${value}`, when the + * number of values is not a multiple of the number of columns, or when the + * column names are not one line of names separated by `|`. * * @example * ```ts @@ -620,7 +620,7 @@ declare module "bun:test" { * }); * ``` */ - each>(strings: TemplateStringsArray, value: unknown, ...values: unknown[]): Test<[Row]>; + each(strings: TemplateStringsArray, value: unknown, ...values: unknown[]): Test<[Row]>; /** * Returns a function that runs for each item in `table`. * diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index 4c7e60a5acba..06a4a626f1d9 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -145,73 +145,58 @@ fn is_template_strings(global: &JSGlobalObject, array: JSValue) -> JsResult) -> Option { +/// The headings of a template table. `header` is `strings[0]`: a newline, one row of names +/// with `|` between them, and a newline. jest-each also takes an empty name, and a row +/// that goes on after a `|` on the next line. Both are malformed here. +fn template_headings(header: EncodedSlice<'_>) -> Option> { let is_space = |i: usize| strings::is_js_whitespace(u32::from(header.char_at(i))); if header.len == 0 || header.char_at(0) != u16::from(b'\n') { return None; } - // Where the match ends when the word at `i` comes after a heading, or after a `|`. - let (mut from_heading, mut from_pipe): (Option, Option) = (None, None); - let mut i = header.len; - loop { - let mut newline_end = None; - while i > 1 && is_space(i - 1) { - if newline_end.is_none() && header.char_at(i - 1) == u16::from(b'\n') { - newline_end = Some(i); - } - i -= 1; - } - if i <= 1 { - return from_pipe; - } - let word_end = i; - while i > 1 && !is_space(i - 1) { - i -= 1; - } - let word_len = word_end - i; - let ends_with_pipe = header.char_at(word_end - 1) == u16::from(b'|'); - // The last `len` characters of the word start with a heading. The heading takes all - // of them: then a `|` word follows, or the match stops at the last newline after the - // word. If that fails, the heading stops before a `|` that ends the word. - let heading_then = |len: usize| { - from_heading.or(newline_end).or(if ends_with_pipe && len >= 2 { from_pipe } else { None }) - }; - (from_heading, from_pipe) = ( - if header.char_at(i) != u16::from(b'|') { - None - } else if word_len == 1 { - from_pipe - } else { - heading_then(word_len - 1) - }, - heading_then(word_len), - ); + let mut i = 1; + while i < header.len && is_space(i) { + i += 1; } -} - -/// `header[..end]` without its whitespace, split on `|`. -fn template_headings(header: EncodedSlice<'_>, end: usize) -> Vec { let mut headings = Vec::new(); let mut heading: Vec = Vec::new(); - for i in 0..end { + let mut heading_ended = false; + loop { + if i == header.len { + return None; + } let unit = header.char_at(i); + if unit == u16::from(b'\n') { + break; + } if unit == u16::from(b'|') { + if heading.is_empty() { + return None; + } headings.push(BunString::clone_utf16(&heading)); heading.clear(); - } else if !strings::is_js_whitespace(u32::from(unit)) { + heading_ended = false; + } else if is_space(i) { + heading_ended = !heading.is_empty(); + } else if heading_ended { + return None; + } else { heading.push(unit); } + i += 1; + } + if heading.is_empty() { + return None; } headings.push(BunString::clone_utf16(&heading)); - headings + // In jest-each, a `|` that starts the next text continues the row. + i += 1; + while i < header.len && is_space(i) { + i += 1; + } + if i < header.len && header.char_at(i) == u16::from(b'|') { + return None; + } + Some(headings) } /// The table for `each(strings, ...values)`: one object per row, keyed by the headings in @@ -235,9 +220,7 @@ fn template_table( let first = template_strings.get_index(global, 0)?; rooted.append(first); let headings = if first.is_string() { - let header = first.to_bun_string(global)?; - let header = header.to_encoded_slice(); - match_template_headings(header).map(|end| template_headings(header, end)) + template_headings(first.to_bun_string(global)?.to_encoded_slice()) } else { None }; diff --git a/test/integration/bun-types/fixture/test.ts b/test/integration/bun-types/fixture/test.ts index bd91e2a63992..f98f6371bc7e 100644 --- a/test/integration/bun-types/fixture/test.ts +++ b/test/integration/bun-types/fixture/test.ts @@ -396,9 +396,23 @@ test.each` a | b | expected ${1} | ${2} | ${3} `("test.each", (row, done) => { - expectType(row).is>(); + expectType(row).is(); expectType(done).is<(err?: unknown) => void>(); }); +test.each` + a | b + ${1} | ${"x"} +`("test.each", ({ a, b }: { a: number; b: string }, done) => { + expectType(a).is(); + expectType(b).is(); + expectType(done).is<(err?: unknown) => void>(); +}); +describe.each` + a + ${1} +`("describe.each", ({ a }: { a: number }) => { + expectType(a).is(); +}); test.each<{ a: number; b: string }>` a | b ${1} | ${"x"} @@ -416,13 +430,13 @@ test.skip.each` a ${1} `.todo("test.each", row => { - expectType(row).is>(); + expectType(row).is(); }); describe.each` a ${1} `("describe.each", row => { - expectType(row).is>(); + expectType(row).is(); }); // a table needs at least one ${value} // @ts-expect-error diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index 87f1f99683e2..337dcac28144 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -167,15 +167,13 @@ describe("tagged template table", () => { Object.assign(cooked, { raw: [...cooked] }) as unknown as TemplateStringsArray; it.each( - strings("\n a||\ud83d\n", "", "", ""), + strings("\n a|\ud83d\n", "", ""), 1, 2, - 3, - )("keeps a heading that is empty or half of a pair", row => { + )("keeps a heading that is half of a surrogate pair", row => { expect(Object.entries(row)).toEqual([ ["a", 1], - ["", 2], - ["\ud83d", 3], + ["\ud83d", 2], ]); }); @@ -249,16 +247,31 @@ describe("tagged template table", () => { }); it("a heading that is empty or has a space in it", () => { - for (const header of ["\n a b | c\n", "\n | a\n", "\n a |\n", "\n a || b\n", "\n \n"]) { + for (const header of ["\n a b | c\n", "\n | a\n", "\n a |\n", "\n a||b\n", "\n \n"]) { + expect(titleCallError(it.each(strings(header, ""), 1))).toBe(badHeadings(JSON.stringify(header))); + } + }); + + it("a heading row that goes on after a newline", () => { + for (const header of ["\n a |\n b\n", "\n a\n | b\n", "\n a\n |\n"]) { expect(titleCallError(it.each(strings(header, ""), 1))).toBe(badHeadings(JSON.stringify(header))); } }); }); - describe("heading grammar", () => { - // jest-each's, from its src/validation.ts and src/bind.ts. + describe("heading row", () => { + // The grammar of jest-each, from its src/validation.ts and src/bind.ts. const HEADINGS = /^\n\s*[^\s]+\s*(\|\s*[^\s]+\s*)*\n/; - const jestHeadings = (header: string) => header.match(HEADINGS)?.[0].replace(/\s/g, "").split("|"); + // bun reads the headings that jest-each reads. Three shapes that jest-each takes are malformed here. + const expectedHeadings = (header: string) => { + const match = header.match(HEADINGS)?.[0]; + if (match === undefined) return undefined; + const names = match.replace(/\s/g, "").split("|"); + const emptyName = names.includes(""); + const rowGoesOnAfterNewline = /\S\s*\n\s*\S/.test(match); + const pipeStartsNextText = header.slice(match.length).trimStart().startsWith("|"); + return emptyName || rowGoesOnAfterNewline || pipeStartsNextText ? undefined : names; + }; const headers = new Set(); const add = (prefix: string, depth: number) => { @@ -269,15 +282,21 @@ describe("tagged template table", () => { for (const header of [ "", " a\n", + "a\n", "\n first | second | third\n ", + "\n\n\ta|b \n c\n", "\n\ta\t|\tb\t\n", "\n a | b\r\n", "\n a\u00a0|\u3000b \n", "\n a\u2028| b\n", - "\n\ufeffa |\n b\n", - "\n a|\n b\n", - "\n a |b| c\n d | e\n", + "\n\ufeffa | b\n", "\n a\u200b | b\n", + "\n a\rb\n", + "\n a\u2028b | c\n", + "\n a |b| c\n d | e\n", + "\n a | b\n | c\n", + "\n a |\n b\n", + "\n a||b\n", "\n 😀 | é\n", "\n \ud83d \n", ]) { @@ -287,10 +306,10 @@ describe("tagged template table", () => { const mismatches: unknown[] = []; let accepted = 0; for (const header of headers) { - const expected = jestHeadings(header); - // One value more than a row takes: the error lists the headings. A table of one column takes any count. - const values = expected && expected.length > 1 ? Array(expected.length + 1).fill(0) : [0]; - const each = (describe.each as any)(strings(header, ""), ...values); + const expected = expectedHeadings(header); + if (expected) accepted++; + // A table of one column takes the one value. With more columns, the error lists the headings. + const each = (describe.each as any)(strings(header, ""), 0); let got: unknown; try { each("one heading", (row: object) => { @@ -302,15 +321,14 @@ describe("tagged template table", () => { } let want: unknown = "Table headings do not conform to expected format:\n\nheading1 | headingN"; if (expected) { - accepted++; want = expected.length > 1 ? "Not enough arguments supplied for given headings:\n" + expected.join(" | ") : 1; } if (got !== want) mismatches.push([header, got, want]); } - it("is the grammar of jest-each", () => { + it("has the headings that jest-each reads, or is malformed", () => { expect(mismatches).toEqual([]); - expect({ headers: headers.size, accepted }).toEqual({ headers: 354, accepted: 137 }); + expect({ headers: headers.size, accepted }).toEqual({ headers: 360, accepted: 53 }); }); }); }); From 9bbaa0413844355f7a8ee4ce97626ea4cd975766 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 1 Oct 2026 21:15:43 +0000 Subject: [PATCH 3/6] test: keep the tagged-template child-run cases in jest-each.test.ts --- test/cli/test/bun-test.test.ts | 113 ---------------------------- test/js/bun/test/jest-each.test.ts | 116 ++++++++++++++++++++++++++++- 2 files changed, 115 insertions(+), 114 deletions(-) diff --git a/test/cli/test/bun-test.test.ts b/test/cli/test/bun-test.test.ts index 610762748d50..49a4905e9b14 100644 --- a/test/cli/test/bun-test.test.ts +++ b/test/cli/test/bun-test.test.ts @@ -1348,119 +1348,6 @@ describe("bun test", () => { expect(stderr).toContain("1 | $missing| $a.b.c| 1"); }); }); - - describe.concurrent("tagged template table", () => { - // Runs one test file. `results` has the line of each test, without the duration. - async function run(contents: string, ...args: string[]) { - using dir = tempDir("bun-test-each-template", { "table.test.ts": contents }); - await using proc = Bun.spawn({ - cmd: [bunExe(), "test", "./table.test.ts", ...args], - env: bunEnv, - cwd: String(dir), - stdout: "pipe", - stderr: "pipe", - }); - const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - const results = stderr - .split(/\r?\n/) - .filter(line => /^\((pass|fail|skip|todo)\) /.test(line)) - .map(line => line.replace(/ \[[\d.]+m?s\]$/, "")); - return { results, stderr: stderr.replaceAll("\r\n", "\n"), exitCode }; - } - - // The first table is from https://github.com/oven-sh/bun/issues/6364. The rows of the second one have to fail. - const tables = ` - import { test, expect } from "bun:test"; - test.each\` - a | b | expected - \${1} | \${2} | \${3} - \${2} | \${2} | \${4} - \`("$a and $b add up to $expected", ({ a, b, expected }) => { - expect(a + b).toBe(expected); - }); - const price = { apple: 3, pear: 4 }; - test.each\` - fruit | expected - \${"apple"} | \${999} - \${"pear"} | \${999} - \`("price of $fruit is $expected", ({ fruit, expected }) => { - expect(price[fruit]).toBe(expected); - }); - `; - - test("runs one test for each row, with the values of the row in the title", async () => { - const { results, exitCode } = await run(tables); - expect({ results, exitCode }).toEqual({ - results: [ - "(pass) 1 and 2 add up to 3", - "(pass) 2 and 2 add up to 4", - "(fail) price of apple is 999", - "(fail) price of pear is 999", - ], - exitCode: 1, - }); - }); - - test("matches -t against the title of each row", async () => { - const { results, exitCode } = await run(tables, "-t", "2 and 2|of pear"); - expect({ results, exitCode }).toEqual({ - results: ["(pass) 2 and 2 add up to 4", "(fail) price of pear is 999"], - exitCode: 1, - }); - }); - - const noValues = - "`.each` called with a Tagged Template Literal with no data, remember to interpolate with ${expression} syntax."; - test.each([ - ["headings and no values", "test.each`\n a | b\n`", [], noValues], - ["no text", "test.each``", [], "`.each` called with an empty Tagged Template Literal of table data."], - ["an invalid escape and no values", "test.each`\\unicode`", [], noValues], - [ - "values that do not fill the last row", - "test.each`\n a | b\n ${1} | ${2}\n ${3}\n`", - [], - "Not enough arguments supplied for given headings:\na | b\n\nReceived:\n[ 1, 2, 3 ]\n\nMissing 1 argument", - ], - [ - "headings on the line of the backtick", - "test.each`a | b\n ${1} | ${2}\n`", - [], - 'Table headings do not conform to expected format:\n\nheading1 | headingN\n\nReceived:\n\n"a | b\\n "', - ], - ["test.skip.each", "test.skip.each`\n a | b\n`", [], noValues], - ["test.todo.each", "test.todo.each`\n a | b\n`", [], noValues], - ["test.failing.each", "test.failing.each`\n a | b\n`", [], noValues], - ["describe.each", "describe.each`\n a | b\n`", [], noValues], - ["a modifier after .each", "test.each`\n a | b\n`.skip", [], noValues], - ["a title that -t filters out", "test.each`\n a | b\n`", ["-t", "sentinel"], noValues], - ])("fails the file for a malformed table: %s", async (_, each, args, message) => { - const { results, stderr, exitCode } = await run( - ` - import { test, describe } from "bun:test"; - ${each}("row $a", () => {}); - test("sentinel", () => {}); - `, - ...args, - ); - expect(stderr).toContain(`error: ${message}\n`); - expect({ rows: results.filter(line => line.includes("row")), exitCode }).toEqual({ rows: [], exitCode: 1 }); - }); - - test("a malformed table that gets no title does not fail the file", async () => { - const { results, exitCode } = await run(` - import { test } from "bun:test"; - test.each\` - a | b - \`; - test.each\` - a | b - \${1} - \`; - test("sentinel", () => {}); - `); - expect({ results, exitCode }).toEqual({ results: ["(pass) sentinel"], exitCode: 0 }); - }); - }); }); test("Prints error when no test matches", () => { diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index 337dcac28144..60b0bfc65e40 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -1,4 +1,5 @@ -import { describe, expect, it } from "bun:test"; +import { describe, expect, it, test } from "bun:test"; +import { bunEnv, bunExe, tempDir } from "harness"; const NUMBERS = [ [1, 1, 2], @@ -331,4 +332,117 @@ describe("tagged template table", () => { expect({ headers: headers.size, accepted }).toEqual({ headers: 360, accepted: 53 }); }); }); + + describe.concurrent("in a test run", () => { + // Runs one test file. `results` has the line of each test, without the duration. + async function run(contents: string, ...args: string[]) { + using dir = tempDir("jest-each-template", { "table.test.ts": contents }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "./table.test.ts", ...args], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + const results = stderr + .split(/\r?\n/) + .filter(line => /^\((pass|fail|skip|todo)\) /.test(line)) + .map(line => line.replace(/ \[[\d.]+m?s\]$/, "")); + return { results, stderr: stderr.replaceAll("\r\n", "\n"), exitCode }; + } + + // The first table is from https://github.com/oven-sh/bun/issues/6364. The rows of the second one have to fail. + const tables = ` + import { test, expect } from "bun:test"; + test.each\` + a | b | expected + \${1} | \${2} | \${3} + \${2} | \${2} | \${4} + \`("$a and $b add up to $expected", ({ a, b, expected }) => { + expect(a + b).toBe(expected); + }); + const price = { apple: 3, pear: 4 }; + test.each\` + fruit | expected + \${"apple"} | \${999} + \${"pear"} | \${999} + \`("price of $fruit is $expected", ({ fruit, expected }) => { + expect(price[fruit]).toBe(expected); + }); + `; + + test("runs one test for each row, with the values of the row in the title", async () => { + const { results, exitCode } = await run(tables); + expect({ results, exitCode }).toEqual({ + results: [ + "(pass) 1 and 2 add up to 3", + "(pass) 2 and 2 add up to 4", + "(fail) price of apple is 999", + "(fail) price of pear is 999", + ], + exitCode: 1, + }); + }); + + test("matches -t against the title of each row", async () => { + const { results, exitCode } = await run(tables, "-t", "2 and 2|of pear"); + expect({ results, exitCode }).toEqual({ + results: ["(pass) 2 and 2 add up to 4", "(fail) price of pear is 999"], + exitCode: 1, + }); + }); + + const noValues = + "`.each` called with a Tagged Template Literal with no data, remember to interpolate with ${expression} syntax."; + test.each([ + ["headings and no values", "test.each`\n a | b\n`", [], noValues], + ["no text", "test.each``", [], "`.each` called with an empty Tagged Template Literal of table data."], + ["an invalid escape and no values", "test.each`\\unicode`", [], noValues], + [ + "values that do not fill the last row", + "test.each`\n a | b\n ${1} | ${2}\n ${3}\n`", + [], + "Not enough arguments supplied for given headings:\na | b\n\nReceived:\n[ 1, 2, 3 ]\n\nMissing 1 argument", + ], + [ + "headings on the line of the backtick", + "test.each`a | b\n ${1} | ${2}\n`", + [], + 'Table headings do not conform to expected format:\n\nheading1 | headingN\n\nReceived:\n\n"a | b\\n "', + ], + ["test.skip.each", "test.skip.each`\n a | b\n`", [], noValues], + ["test.todo.each", "test.todo.each`\n a | b\n`", [], noValues], + ["test.failing.each", "test.failing.each`\n a | b\n`", [], noValues], + ["describe.each", "describe.each`\n a | b\n`", [], noValues], + ["a modifier after .each", "test.each`\n a | b\n`.skip", [], noValues], + ["a title that -t filters out", "test.each`\n a | b\n`", ["-t", "sentinel"], noValues], + ])("fails the file for a malformed table: %s", async (_, each, args, message) => { + const { results, stderr, exitCode } = await run( + ` + import { test, describe } from "bun:test"; + ${each}("row $a", () => {}); + test("sentinel", () => {}); + `, + ...args, + ); + expect(stderr).toContain(`error: ${message}\n`); + expect({ rows: results.filter(line => line.includes("row")), exitCode }).toEqual({ rows: [], exitCode: 1 }); + }); + + test("a malformed table that gets no title does not fail the file", async () => { + const { results, exitCode } = await run(` + import { test } from "bun:test"; + test.each\` + a | b + \`; + test.each\` + a | b + \${1} + \`; + test("sentinel", () => {}); + `); + expect({ results, exitCode }).toEqual({ results: ["(pass) sentinel"], exitCode: 0 }); + }); + }); }); From f829cf13e055b7ee21135b4ff56134c448f53196 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 03:18:41 +0000 Subject: [PATCH 4/6] bun:test: take value rows that start with | in a template table A `|` at the start of the text after the heading row made the table malformed. jest-each reads more headings there only when a name follows the `|`. Now a `|` with no name after it starts a row of values, so a table with `| ${1} | ${2} |` rows runs as it does in Jest. A `|` and a name at the start of the next line stay malformed, with or without a newline after the name. --- src/runtime/test_runner/ScopeFunctions.rs | 23 ++++++++++++----------- test/js/bun/test/jest-each.test.ts | 21 ++++++++++++++++----- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index 06a4a626f1d9..fefc1cc68fae 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -147,16 +147,19 @@ fn is_template_strings(global: &JSGlobalObject, array: JSValue) -> JsResult) -> Option> { let is_space = |i: usize| strings::is_js_whitespace(u32::from(header.char_at(i))); + let skip_space = |mut i: usize| { + while i < header.len && is_space(i) { + i += 1; + } + i + }; if header.len == 0 || header.char_at(0) != u16::from(b'\n') { return None; } - let mut i = 1; - while i < header.len && is_space(i) { - i += 1; - } + let mut i = skip_space(1); let mut headings = Vec::new(); let mut heading: Vec = Vec::new(); let mut heading_ended = false; @@ -188,12 +191,10 @@ fn template_headings(header: EncodedSlice<'_>) -> Option> { return None; } headings.push(BunString::clone_utf16(&heading)); - // In jest-each, a `|` that starts the next text continues the row. - i += 1; - while i < header.len && is_space(i) { - i += 1; - } - if i < header.len && header.char_at(i) == u16::from(b'|') { + // jest-each can read a `|` and a name at the start of the next line as more headings. + // A `|` with no name after it starts a row of values. + i = skip_space(i + 1); + if i < header.len && header.char_at(i) == u16::from(b'|') && skip_space(i + 1) < header.len { return None; } Some(headings) diff --git a/test/js/bun/test/jest-each.test.ts b/test/js/bun/test/jest-each.test.ts index 60b0bfc65e40..d8ea9ffd919e 100644 --- a/test/js/bun/test/jest-each.test.ts +++ b/test/js/bun/test/jest-each.test.ts @@ -158,6 +158,15 @@ describe("tagged template table", () => { expect(row.b - row.a).toBe(1); }); + eachOf` + a | b + | ${1} | ${2} | + | ${3} | ${4} | + `("takes value rows that start with |", row => { + expect(Reflect.ownKeys(row)).toEqual(["a", "b"]); + expect(row.b - row.a).toBe(1); + }); + // @ts-expect-error an array table takes one argument it.each([[1, 2]], "ignored")("an array with more arguments after it is an array table: %d %d", (a, b) => { expect([a, b]).toEqual([1, 2]); @@ -253,8 +262,8 @@ describe("tagged template table", () => { } }); - it("a heading row that goes on after a newline", () => { - for (const header of ["\n a |\n b\n", "\n a\n | b\n", "\n a\n |\n"]) { + it("a heading row on two lines", () => { + for (const header of ["\n a |\n b\n", "\n a\n | b\n", "\n a\n |b"]) { expect(titleCallError(it.each(strings(header, ""), 1))).toBe(badHeadings(JSON.stringify(header))); } }); @@ -270,8 +279,8 @@ describe("tagged template table", () => { const names = match.replace(/\s/g, "").split("|"); const emptyName = names.includes(""); const rowGoesOnAfterNewline = /\S\s*\n\s*\S/.test(match); - const pipeStartsNextText = header.slice(match.length).trimStart().startsWith("|"); - return emptyName || rowGoesOnAfterNewline || pipeStartsNextText ? undefined : names; + const pipeAndNameStartNextText = /^\s*\|\s*\S/.test(header.slice(match.length)); + return emptyName || rowGoesOnAfterNewline || pipeAndNameStartNextText ? undefined : names; }; const headers = new Set(); @@ -296,6 +305,8 @@ describe("tagged template table", () => { "\n a\u2028b | c\n", "\n a |b| c\n d | e\n", "\n a | b\n | c\n", + "\n a | b\n | ", + "\n a | b\n |c", "\n a |\n b\n", "\n a||b\n", "\n 😀 | é\n", @@ -329,7 +340,7 @@ describe("tagged template table", () => { it("has the headings that jest-each reads, or is malformed", () => { expect(mismatches).toEqual([]); - expect({ headers: headers.size, accepted }).toEqual({ headers: 360, accepted: 53 }); + expect({ headers: headers.size, accepted }).toEqual({ headers: 362, accepted: 63 }); }); }); From c3028eeffb12d52ae03b4d445b52d60395271ac2 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:14:34 +0000 Subject: [PATCH 5/6] test: say why the template-table GC tests have a timeout In a debug ASAN build the child takes 3.5 s to start when it collects at every third slow allocation. The three tests take 3 s to 7 s there, so the default timeout of 5 s is not enough. --- test/js/bun/test/jest-each-gc-root.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/js/bun/test/jest-each-gc-root.test.ts b/test/js/bun/test/jest-each-gc-root.test.ts index 73791225fbae..bdcae1432d41 100644 --- a/test/js/bun/test/jest-each-gc-root.test.ts +++ b/test/js/bun/test/jest-each-gc-root.test.ts @@ -185,6 +185,7 @@ test("the rows of a test.each/describe.each template table are a GC root", async expect(stderr).toContain(" 4 pass"); expect(stderr).toContain(" 0 fail"); expect(exitCode).toBe(0); + // A debug ASAN build takes 4 s: the child collects all the time from its start. }, 60_000); // A collection runs while .each builds the rows, and while it makes the function that keeps @@ -225,5 +226,6 @@ test.concurrent.each([3, 4])( expect(stderr).toContain(" 0 fail"); expect(exitCode).toBe(0); }, + // A debug ASAN build takes 7 s: the child collects this often from its start. 60_000, ); From ad90f9a55dc68403f60ddf0ba49b6f6aea431d88 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:35:08 +0000 Subject: [PATCH 6/6] bun:test: keep each new comment in ScopeFunctions.rs to one line --- src/runtime/test_runner/ScopeFunctions.rs | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/src/runtime/test_runner/ScopeFunctions.rs b/src/runtime/test_runner/ScopeFunctions.rs index fefc1cc68fae..9710030a9054 100644 --- a/src/runtime/test_runner/ScopeFunctions.rs +++ b/src/runtime/test_runner/ScopeFunctions.rs @@ -58,11 +58,10 @@ pub enum Mode { pub(crate) struct ScopeFunctions { pub(crate) mode: Mode, pub(crate) cfg: BaseScopeCfg, - /// typically `.zero`. After `.each`: the table array, or the Error of a malformed - /// template table, which the title call throws. not Strong.Optional because codegen - /// visits the C++ `m_each` WriteBarrier on the JS wrapper (see `values: ["each"]` in - /// jest.classes.ts). This field is kept in sync with that slot via - /// `js::each_set_cached` in `create_unbound`. + /// typically `.zero`. not Strong.Optional because codegen visits the C++ `m_each` + /// WriteBarrier on the JS wrapper (see `values: ["each"]` in jest.classes.ts). This + /// field is kept in sync with that slot via `js::each_set_cached` in `create_unbound`. + /// After `.each`: the table array, or the Error of a malformed template table. pub(crate) each: JSValue, } @@ -145,9 +144,7 @@ fn is_template_strings(global: &JSGlobalObject, array: JSValue) -> JsResult) -> Option> { let is_space = |i: usize| strings::is_js_whitespace(u32::from(header.char_at(i))); let skip_space = |mut i: usize| { @@ -192,7 +189,6 @@ fn template_headings(header: EncodedSlice<'_>) -> Option> { } headings.push(BunString::clone_utf16(&heading)); // jest-each can read a `|` and a name at the start of the next line as more headings. - // A `|` with no name after it starts a row of values. i = skip_space(i + 1); if i < header.len && header.char_at(i) == u16::from(b'|') && skip_space(i + 1) < header.len { return None; @@ -200,9 +196,7 @@ fn template_headings(header: EncodedSlice<'_>) -> Option> { Some(headings) } -/// The table for `each(strings, ...values)`: one object per row, keyed by the headings in -/// `strings[0]`. A malformed table gives the Error that the title call throws, in -/// jest-each's wording. `rooted` keeps the result alive until the caller stores it. +/// One object per row of `each(strings, ...values)`, or the Error that the title call throws. fn template_table( global: &JSGlobalObject, rooted: &mut bun_jsc::MarkedArgumentBuffer, @@ -273,8 +267,7 @@ fn template_table( Ok(rows) } -/// A template with no `${}` calls `each(strings)`, so `.each` kept `strings` as a table of one row. -/// That row is the text of the template, or undefined when the text has an invalid escape. +/// A template with no `${}` is a table of one row here: its text, or undefined for an invalid escape. fn reject_template_without_values(global: &JSGlobalObject, table: JSValue) -> JsResult<()> { let first = table.get_index(global, 0)?; if !(first.is_string() || first.is_undefined()) || !is_template_strings(global, table)? {