Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions docs/test/writing-tests.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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. The title takes the same `$name` placeholders as for a table of objects.

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, 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 }>`
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 column names are not one line of names with `|` between them

### Format Specifiers

Use these specifiers to format the test title:
Expand Down
52 changes: 52 additions & 0 deletions packages/bun-types/test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,33 @@ declare module "bun:test" {
* @param condition if these tests should be marked TODO
*/
todoIf(condition: boolean): Describe<T>;
/**
* 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, annotate the parameter or pass the type argument:
* `describe.each<{ a: number }>`.
*
* 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
* 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<Row = any>(strings: TemplateStringsArray, value: unknown, ...values: unknown[]): Describe<[Row]>;
/**
* Returns a function that runs for each item in `table`.
*
Expand Down Expand Up @@ -588,6 +615,31 @@ declare module "bun:test" {
* @param condition if the test should run serially
*/
serialIf(condition: boolean): Test<T>;
/**
* 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, annotate the parameter or pass the type argument:
* `test.each<{ a: number }>`.
*
* 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
* test.each`
* a | b | expected
* ${1} | ${2} | ${3}
* ${4} | ${5} | ${9}
* `("add($a, $b) = $expected", ({ a, b, expected }) => {
* expect(a + b).toBe(expected);
* });
* ```
*/
each<Row = any>(strings: TemplateStringsArray, value: unknown, ...values: unknown[]): Test<[Row]>;
/**
* Returns a function that runs for each item in `table`.
*
Expand Down
165 changes: 163 additions & 2 deletions src/runtime/test_runner/ScopeFunctions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -61,6 +61,7 @@ pub(crate) struct ScopeFunctions {
/// 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,
}

Expand Down Expand Up @@ -117,7 +118,8 @@ impl ScopeFunctions {
pub(crate) fn fn_each(this: &Self, global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
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))));
Expand All @@ -126,10 +128,163 @@ 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<bool> {
Ok(array.get_own_truthy(global, "raw")?.is_some_and(|raw| raw.is_array()))
}

/// The headings in `strings[0]`: one row of names. jest-each also takes an empty name and a row on two lines.
fn template_headings(header: EncodedSlice<'_>) -> Option<Vec<BunString>> {
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 = skip_space(1);
let mut headings = Vec::new();
let mut heading: Vec<u16> = Vec::new();
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();
heading_ended = false;
} else if is_space(i) {
heading_ended = !heading.is_empty();
} else if heading_ended {
return None;
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
} else {
heading.push(unit);
}
i += 1;
}
if heading.is_empty() {
return None;
}
headings.push(BunString::clone_utf16(&heading));
// jest-each can read a `|` and a name at the start of the next line as more headings.
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)
}

/// 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,
template_strings: JSValue,
values: &[JSValue],
) -> JsResult<JSValue> {
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() {
template_headings(first.to_bun_string(global)?.to_encoded_slice())
} 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<u8> = 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" },
),
);
}

Comment thread
robobun marked this conversation as resolved.
Resolved
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 `${}` 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)? {
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<JSValue> {
let _g = group_log::begin();
Expand Down Expand Up @@ -168,10 +323,16 @@ fn call_as_function(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSVa

if !this.each.is_empty() {
if this.each.is_undefined_or_null() || !this.each.is_array() {
if this.each.is_error() {
return Err(global.throw_value(this.each));
}
let mut formatter = bun_jsc::ConsoleObject::Formatter::new(global);
return Err(global.throw(format_args!("Expected array, got {}", this.each.to_fmt(&mut formatter))));
}
let mut iter = this.each.array_iterator(global)?;
if iter.len == 1 {
reject_template_without_values(global, this.each)?;
}
let mut test_idx: usize = 0;
while let Some(item) = iter.next()? {
if item.is_empty() {
Expand Down
48 changes: 48 additions & 0 deletions test/integration/bun-types/fixture/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,54 @@ expect(await query()).toEqual([{ x: 1 }]);
expect(await query<number>()).toBe(1);
expectType<Matchers<undefined>>(expect());

// tagged template table: one row object per test
test.each`
a | b | expected
${1} | ${2} | ${3}
`("test.each", (row, done) => {
expectType(row).is<any>();
expectType(done).is<(err?: unknown) => void>();
});
test.each`
a | b
${1} | ${"x"}
`("test.each", ({ a, b }: { a: number; b: string }, done) => {
expectType(a).is<number>();
expectType(b).is<string>();
expectType(done).is<(err?: unknown) => void>();
});
describe.each`
a
${1}
`("describe.each", ({ a }: { a: number }) => {
expectType(a).is<number>();
});
test.each<{ a: number; b: string }>`
a | b
${1} | ${"x"}
`("test.each", ({ a, b }) => {
expectType(a).is<number>();
expectType(b).is<string>();
});
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<any>();
});
describe.each`
a
${1}
`("describe.each", row => {
expectType(row).is<any>();
});

// Advanced use case tests for #18511:

// 1. => When assignable to, we should pass (e.g. new Set() is assignable to Set<string>).
Expand Down
Loading
Loading