diff --git a/flow-typed/environment/jest.js b/flow-typed/environment/jest.js index d3cc6126ebb0..4cbbf62b284d 100644 --- a/flow-typed/environment/jest.js +++ b/flow-typed/environment/jest.js @@ -1035,11 +1035,33 @@ declare var describe: { /** * Only run this describe block */ - only(name: JestTestName, fn: () => void): void, + only: { + (name: JestTestName, fn: () => void): void, + each( + ...table: + | ReadonlyArray | unknown> + | [ReadonlyArray, string] + ): ( + name: JestTestName, + fn?: (...args: ReadonlyArray) => any, + timeout?: number, + ) => void, + }, /** * Skip running this describe block */ - skip(name: JestTestName, fn: () => void): void, + skip: { + (name: JestTestName, fn: () => void): void, + each( + ...table: + | ReadonlyArray | unknown> + | [ReadonlyArray, string] + ): ( + name: JestTestName, + fn?: (...args: ReadonlyArray) => any, + timeout?: number, + ) => void, + }, /** * each runs this test against array of argument arrays per each run * @@ -1136,11 +1158,7 @@ declare var it: { ... }; -declare function fit( - name: JestTestName, - fn: JestProvidesCallback, - timeout?: number, -): void; +declare var fit: typeof it.only; /** An individual test unit */ declare var test: typeof it; /** A disabled group of tests */ diff --git a/private/react-native-fantom/__docs__/README.md b/private/react-native-fantom/__docs__/README.md index 6464ece71d2c..5fde6a1efa6c 100644 --- a/private/react-native-fantom/__docs__/README.md +++ b/private/react-native-fantom/__docs__/README.md @@ -81,7 +81,7 @@ file. The high level structure of Fantom tests is similar to Jest unit tests. However, only a subset of Jest's Global API is currently available. For example, -`test.each` is not yet implemented in Fantom. We are working on adding more Jest +`test.todo` is not yet implemented in Fantom. We are working on adding more Jest APIs. If you are blocked by the lack of a specific API, please reach out to us. Most of the interesting APIs are available via the `@react-native/fantom` @@ -351,7 +351,7 @@ expect(root.getRenderedOutput().toJSX()).toEqual( ### Limitations - `Fantom.runTask()` calls cannot be nested — doing so will throw. -- Only a subset of Jest's Global API is available (e.g. `test.each` is not +- Only a subset of Jest's Global API is available (e.g. `test.todo` is not implemented). Reach out if you're blocked by a specific missing API. - Tests must live within `packages/react-native`; Fantom is not currently intended for application-specific code. diff --git a/private/react-native-fantom/runtime/__tests__/setup-test.js b/private/react-native-fantom/runtime/__tests__/setup-test.js index a16920c720de..04dfadbc70ba 100644 --- a/private/react-native-fantom/runtime/__tests__/setup-test.js +++ b/private/react-native-fantom/runtime/__tests__/setup-test.js @@ -62,7 +62,7 @@ afterEach(() => { } }); -function results() { +function suiteReport() { const NativeFantom = require('../../../../packages/react-native/src/private/testing/fantom/specs/NativeFantom').default; let report; @@ -72,7 +72,11 @@ function results() { report = JSON.parse(json); }); global.$$RunTests$$(); - return report?.testResults ?? []; + return report; +} + +function results() { + return suiteReport()?.testResults ?? []; } it('runs teardown after a failed test before running the next test', () => { @@ -237,3 +241,357 @@ for (const screenshotPosition of ['test', 'teardown']) { ); }); } + +it('declares a test per row of an array table, spreading its values and formatting the title', () => { + const {registerTest} = require('../setup'); + const calls = []; + registerTest( + () => { + it.each([ + [1, 1, 2], + [2, 3, 5], + ])('%i + %i = %i (row %# of %$)', (a, b, sum) => { + calls.push([a, b, sum]); + }); + test.each([-0, 'a%b'])('%d %s %%', value => { + calls.push([value]); + }); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => [result.title, result.status])).toEqual([ + ['1 + 1 = 2 (row 0 of 1)', 'passed'], + ['2 + 3 = 5 (row 1 of 2)', 'passed'], + ['-0 %s %', 'passed'], + ['NaN %s %', 'passed'], + ]); + jestExpect(calls).toEqual([[1, 1, 2], [2, 3, 5], [-0], ['a%b']]); +}); + +it('formats every value placeholder', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + it.each([[{a: [1]}, {b: 2}, 'text', 10n, 1.5, '42px', 3.7]])( + '%p %j %s %d %f %i %i', + () => {}, + ); + it.each([[{a: 1}, [2], {b: 3}, '%s', 'x']])('%o %O %s %s %s', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => result.title)).toEqual([ + '{"a": [Array]} {"b":2} text 10n 1.5 42 3', + '{"a": 1} [2] {"b": 3} %s x', + ]); +}); + +it('formats %i and %s as jest-each does, and keeps a placeholder a printed value holds', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + it.each([['0x1A', {toString: () => '(1, 2)'}, {unit: '%d'}, 5]])( + 'code %i moves to %s at %p costs %d', + () => {}, + ); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => result.title)).toEqual([ + 'code 26 moves to (1, 2) at {"unit": "%d"} costs 5', + ]); +}); + +it('leaves a %c and a second %# in the title as written', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + it.each([['x']])('%c %s', () => {}); + it.each([['x']])('%# %#', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => result.title)).toEqual(['%c x', '0 %#']); +}); + +it('interpolates the fields of an object table into the title', () => { + const {registerTest} = require('../setup'); + const rows = []; + registerTest( + () => { + describe.each([ + {name: 'first', nested: {value: 1}, component: function Banner() {}}, + {name: 'second', nested: {value: 2}, component: function Card() {}}, + ])( + '$name ($name.length, $component.name, $nested.value, $nested, row $#)', + row => { + it('runs', () => { + rows.push(row.name); + }); + }, + ); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect( + results().map(result => [result.ancestorTitles, result.title]), + ).toEqual([ + [['first (5, Banner, 1, {"value": 1}, row 0)'], 'runs'], + [['second (6, Card, 2, {"value": 2}, row 1)'], 'runs'], + ]); + jestExpect(rows).toEqual(['first', 'second']); +}); + +it('declares a test per row of a tagged template table', () => { + const {registerTest} = require('../setup'); + const rows = []; + registerTest( + () => { + it.each` + a | b | sum + ${1} | ${1} | ${2} + ${2} | ${3} | ${5} + `('$a + $b = $sum', row => { + rows.push(row); + }); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => result.title)).toEqual([ + '1 + 1 = 2', + '2 + 3 = 5', + ]); + jestExpect(rows).toEqual([ + {a: 1, b: 1, sum: 2}, + {a: 2, b: 3, sum: 5}, + ]); +}); + +it('focuses and skips the rows of only.each and skip.each', () => { + const {registerTest} = require('../setup'); + const calls = []; + registerTest( + () => { + it('unfocused', () => { + calls.push('unfocused'); + }); + // eslint-disable-next-line jest/no-focused-tests + it.only.each([1, 2])('focused %i', value => { + calls.push(`focused ${value}`); + }); + // eslint-disable-next-line jest/no-focused-tests + describe.only.each([3])('focused suite %i', value => { + it('inner', () => { + calls.push(`focused suite ${value}`); + }); + }); + // eslint-disable-next-line jest/no-disabled-tests + describe.skip.each([4])('skipped suite %i', value => { + // eslint-disable-next-line jest/no-focused-tests + it.only('inner', () => { + calls.push(`skipped suite ${value}`); + }); + }); + // eslint-disable-next-line jest/no-disabled-tests + it.skip.each([5])('skipped %i', value => { + calls.push(`skipped ${value}`); + }); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect( + results().map(result => [ + result.ancestorTitles, + result.title, + result.status, + ]), + ).toEqual([ + [[], 'unfocused', 'pending'], + [[], 'focused 1', 'passed'], + [[], 'focused 2', 'passed'], + [['focused suite 3'], 'inner', 'passed'], + [['skipped suite 4'], 'inner', 'pending'], + [[], 'skipped 5', 'pending'], + ]); + jestExpect(calls).toEqual(['focused 1', 'focused 2', 'focused suite 3']); +}); + +it('skips the rows of skip.each with nothing focused', () => { + const {registerTest} = require('../setup'); + const calls = []; + registerTest( + () => { + it('runs', () => { + calls.push('runs'); + }); + // eslint-disable-next-line jest/no-disabled-tests + it.skip.each([1])('skipped %i', value => { + calls.push(`skipped ${value}`); + }); + // eslint-disable-next-line jest/no-disabled-tests + describe.skip.each([2])('skipped suite %i', value => { + it('inner', () => { + calls.push(`skipped suite ${value}`); + }); + }); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect( + results().map(result => [ + result.ancestorTitles, + result.title, + result.status, + ]), + ).toEqual([ + [[], 'runs', 'passed'], + [[], 'skipped 1', 'pending'], + [['skipped suite 2'], 'inner', 'pending'], + ]); + jestExpect(calls).toEqual(['runs']); +}); + +it('reports a table it cannot read with its message and the test file as its first frame', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + it.each([])('empty', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + const [empty] = results(); + jestExpect(empty.failureMessages[0]).toMatch( + /^Error: Error: `\.each` called with an empty Array of table data\.\n\n {4}at .*setup-test\.js/, + ); +}); + +it('fails the file for a describe.each table it cannot read, as a throwing describe does', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + describe.each([])('empty', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(suiteReport()?.error?.message).toBe( + 'Error: `.each` called with an empty Array of table data.\n', + ); +}); + +it('declares one failing test, with the message jest-each gives, for a table it cannot read', () => { + const {registerTest} = require('../setup'); + const notATable = 'not a table'; + registerTest( + () => { + // $FlowExpectedError[incompatible-type] + it.each(notATable)('not an array', () => {}); + it.each([])('empty', () => {}); + it.each``('empty template', () => {}); + it.each` + a | b + `('template without data', () => {}); + it.each`${1}`('template without headings', () => {}); + it.each` + a | b + ${1} + `('incomplete', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect( + results().map(result => [ + result.title, + result.status, + result.failureDetails[0]?.message, + ]), + ).toEqual([ + [ + 'not an array', + 'failed', + '`.each` must be called with an Array or Tagged Template Literal.\n\n' + + 'Instead was called with: "not a table"\n', + ], + [ + 'empty', + 'failed', + 'Error: `.each` called with an empty Array of table data.\n', + ], + [ + 'empty template', + 'failed', + 'Error: `.each` called with an empty Tagged Template Literal of table data.\n', + ], + [ + 'template without data', + 'failed', + 'Error: `.each` called with a Tagged Template Literal with no data, ' + + 'remember to interpolate with ${expression} syntax.\n', + ], + [ + 'template without headings', + 'failed', + 'Table headings do not conform to expected format:\n\n' + + 'heading1 | headingN\n\nReceived:\n\n""', + ], + [ + 'incomplete', + 'failed', + 'Not enough arguments supplied for given headings:\na | b\n\n' + + 'Received:\nArray [\n 1,\n]\n\nMissing 1 argument', + ], + ]); +}); + +it('declares one failing test for template headings that are not a string and for a function title', () => { + const {registerTest} = require('../setup'); + function add(value: number) { + return value; + } + registerTest( + () => { + it.each([1], 2)('non-string headings', () => {}); + it.each([[1]])(add, () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect( + results().map(result => [result.status, result.failureDetails[0]?.message]), + ).toEqual([ + [ + 'failed', + 'Table headings do not conform to expected format:\n\n' + + 'heading1 | headingN\n\nReceived:\n\n1', + ], + ['failed', 'title.replaceAll is not a function'], + ]); +}); + +it('reads a getter of an object table row into the title', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + const row = Object.defineProperty({}, 'label', { + enumerable: true, + get: () => 'computed', + }); + it.each([row])('$label $label.length', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => result.title)).toEqual(['computed 8']); +}); + +it('routes an object table by the placeholders of its title', () => { + const {registerTest} = require('../setup'); + registerTest( + () => { + it.each([{a: 1}])('$a %%', () => {}); + it.each([{a: 1}])('%p', () => {}); + }, + {data: {}, updateSnapshot: 'none'}, + ); + jestExpect(results().map(result => result.title)).toEqual([ + '1 %', + '{"a": 1}', + ]); +}); diff --git a/private/react-native-fantom/runtime/each.js b/private/react-native-fantom/runtime/each.js new file mode 100644 index 000000000000..062db432024e --- /dev/null +++ b/private/react-native-fantom/runtime/each.js @@ -0,0 +1,340 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import {format} from 'pretty-format'; + +type Declaration = (title: string, implementation: () => unknown) => void; + +type RowImplementation = (...args: ReadonlyArray) => unknown; + +export type EachDeclaration = ( + table: unknown, + ...templateValues: ReadonlyArray +) => (title: string, implementation: RowImplementation) => void; + +type Row = { + title: string, + arguments: ReadonlyArray, +}; + +const ESCAPED_PERCENT = '%%'; +const PERCENT_ESCAPE = '@@__FANTOM_EACH_PERCENT_ESCAPE__@@'; +const INDEX_PLACEHOLDER = '%#'; +const NUMBER_PLACEHOLDER = '%$'; +const PLACEHOLDER = /%[#Odfijops]/; +const VALUE_PLACEHOLDER = /%[Odfijops]/; +const TEMPLATE_HEADINGS = /^\n\s*[^\s]+\s*(\|\s*[^\s]+\s*)*\n/; + +/** + * Creates the `each` of a test or suite declaration, as `jest-each` documents + * it: https://jestjs.io/docs/api#testeachtablename-fn-timeout + */ +export default function createEach(declare: Declaration): EachDeclaration { + return (table, ...templateValues) => + function declareRows(title, implementation) { + let rows; + try { + rows = + templateValues.length === 0 + ? arrayTableRows(title, table) + : templateTableRows(title, table, templateValues); + } catch (error: unknown) { + if (error instanceof Error) { + Error.captureStackTrace(error, declareRows); + } + declare(title, () => { + throw error; + }); + return; + } + for (const row of rows) { + declare(row.title, () => implementation(...row.arguments)); + } + }; +} + +function arrayTableRows(title: string, table: unknown): Array { + if (!Array.isArray(table)) { + throw new TypeError( + '`.each` must be called with an Array or Tagged Template Literal.\n\n' + + `Instead was called with: ${prettyValue(table)}\n`, + ); + } + if (Object.hasOwn(table, 'raw')) { + const [headingsLine] = table; + if (typeof headingsLine === 'string' && headingsLine.trim() === '') { + throw new Error( + 'Error: `.each` called with an empty Tagged Template Literal of table data.\n', + ); + } + throw new Error( + 'Error: `.each` called with a Tagged Template Literal with no data, ' + + 'remember to interpolate with ${expression} syntax.\n', + ); + } + if (table.length === 0) { + throw new Error( + 'Error: `.each` called with an empty Array of table data.\n', + ); + } + + const isTableOfArrays = table.every(row => Array.isArray(row)); + const objectRows = isTableOfArrays ? null : objectRowsOf(table); + if ( + objectRows != null && + !PLACEHOLDER.test(title.replaceAll(ESCAPED_PERCENT, PERCENT_ESCAPE)) + ) { + return objectRows.map((row, index) => ({ + title: interpolateVariables(title, row, index).replaceAll( + ESCAPED_PERCENT, + '%', + ), + arguments: [row], + })); + } + + return table.map((row, index) => { + const values = isTableOfArrays && Array.isArray(row) ? row : [row]; + return {title: formatTitle(title, values, index), arguments: values}; + }); +} + +function objectRowsOf(table: ReadonlyArray): ?Array { + const rows: Array = []; + for (const row of table) { + if (row == null || typeof row !== 'object') { + return null; + } + rows.push(row); + } + return rows; +} + +function templateTableRows( + title: string, + table: unknown, + values: ReadonlyArray, +): Array { + const headingsLine = Array.isArray(table) ? table[0] : undefined; + const headingsMatch = + typeof headingsLine === 'string' + ? headingsLine.match(TEMPLATE_HEADINGS) + : null; + if (headingsMatch == null) { + throw new Error( + 'Table headings do not conform to expected format:\n\n' + + `heading1 | headingN\n\nReceived:\n\n${format(headingsLine)}`, + ); + } + const headings = headingsMatch[0].replaceAll(/\s/g, '').split('|'); + + const incompleteRowLength = values.length % headings.length; + if (incompleteRowLength > 0) { + const missing = headings.length - incompleteRowLength; + throw new Error( + `Not enough arguments supplied for given headings:\n${headings.join(' | ')}\n\n` + + `Received:\n${format(values)}\n\n` + + `Missing ${missing} ${missing === 1 ? 'argument' : 'arguments'}`, + ); + } + + const rows: Array = []; + for (let start = 0; start < values.length; start += headings.length) { + const row = Object.fromEntries( + headings.map((heading, offset) => [heading, values[start + offset]]), + ); + rows.push({ + title: interpolateVariables(title, row, rows.length), + arguments: [row], + }); + } + return rows; +} + +function formatTitle( + title: string, + values: ReadonlyArray, + index: number, +): string { + let formatted = title + .replaceAll(ESCAPED_PERCENT, PERCENT_ESCAPE) + .replace(INDEX_PLACEHOLDER, String(index)) + .replace(NUMBER_PLACEHOLDER, String(index + 1)); + let searchFrom = 0; + for (const value of values) { + const placeholder = VALUE_PLACEHOLDER.exec(formatted.slice(searchFrom)); + if (placeholder == null) { + break; + } + const start = searchFrom + placeholder.index; + const text = formatPlaceholder(placeholder[0], value); + formatted = + formatted.slice(0, start) + + text + + formatted.slice(start + placeholder[0].length); + searchFrom = start + text.length; + } + return formatted.replaceAll(PERCENT_ESCAPE, '%'); +} + +// jest-each formats with Node's `util.format` and `util.inspect`, which Hermes +// cannot load, so `%o`, `%O` and an object under `%s` whose `toString` is a +// built-in one print as `%p` does. +function formatPlaceholder(placeholder: string, value: unknown): string { + switch (placeholder) { + case '%s': + return formatString(value); + case '%d': + return typeof value === 'bigint' + ? `${String(value)}n` + : typeof value === 'symbol' + ? 'NaN' + : formatNumber(Number(value)); + case '%i': + return formatInteger(value); + case '%f': + return typeof value === 'symbol' + ? 'NaN' + : formatNumber(parseFloat(String(value))); + case '%j': + return stringifyJson(value); + default: + return prettyValue(value); + } +} + +// Node's `util.format` prints an object whose `toString` the code defines with +// that `toString`; a built-in one is native code. +function hasDefinedToString(value: interface {}): boolean { + const toString = Reflect.get(value, 'toString'); + return ( + typeof toString === 'function' && + !Reflect.apply(Function.prototype.toString, toString, []).includes( + '[native code]', + ) + ); +} + +function formatString(value: unknown): string { + if ( + typeof value === 'object' && + value != null && + !hasDefinedToString(value) + ) { + return prettyValue(value); + } + if (typeof value === 'bigint') { + return `${String(value)}n`; + } + if (typeof value === 'number') { + return formatNumber(value); + } + return String(value); +} + +function formatInteger(value: unknown): string { + if (typeof value === 'bigint') { + return `${String(value)}n`; + } + if (typeof value === 'symbol') { + return 'NaN'; + } + // `util.format` parses `%i` with no radix, so `'0x1A'` gives 26. + // eslint-disable-next-line radix + return formatNumber(parseInt(String(value))); +} + +function formatNumber(value: number): string { + return Object.is(value, -0) ? '-0' : String(value); +} + +function stringifyJson(value: unknown): string { + if (isCyclic(value, [])) { + return '[Circular]'; + } + return String( + JSON.stringify(value, (_key, entry: unknown) => + typeof entry === 'bigint' ? `${String(entry)}n` : entry, + ), + ); +} + +function isCyclic(value: unknown, ancestors: ReadonlyArray): boolean { + if (value == null || typeof value !== 'object') { + return false; + } + if (ancestors.includes(value)) { + return true; + } + const nested = [...ancestors, value]; + return Object.values(value).some(entry => isCyclic(entry, nested)); +} + +function interpolateVariables( + title: string, + row: interface {}, + index: number, +): string { + const keys = Object.keys(row) + .filter(key => key.length > 0) + .sort((a, b) => b.length - a.length); + if (keys.length === 0) { + return title.replace('$#', String(index)); + } + const variable = new RegExp( + `\\$(${keys.map(escapeRegExp).join('|')})[.\\w]*`, + 'g', + ); + return title + .replaceAll(variable, match => { + const value = getPath(row, match.slice(1).split('.')); + return isPrimitive(value) ? String(value) : prettyValue(value); + }) + .replace('$#', String(index)); +} + +function getPath(value: unknown, path: ReadonlyArray): unknown { + if (value === null) { + return 'null'; + } + if (value === undefined) { + return 'undefined'; + } + const [head, ...tail] = path; + if (head == null || head === '') { + return value; + } + // jest-each follows an own property of any value: a string's `length`, a + // function's `name`. + const property = Object.getOwnPropertyDescriptor(value, head); + if (property == null) { + return value; + } + return getPath( + property.get != null + ? Reflect.apply(property.get, value, []) + : property.value, + tail, + ); +} + +function isPrimitive(value: unknown): boolean { + return ( + value === null || (typeof value !== 'object' && typeof value !== 'function') + ); +} + +function escapeRegExp(text: string): string { + return text.replaceAll(/[$()*+.?[\\\]^{|}]/g, '\\$&'); +} + +function prettyValue(value: unknown): string { + return format(value, {maxDepth: 1, min: true}); +} diff --git a/private/react-native-fantom/runtime/setup.js b/private/react-native-fantom/runtime/setup.js index 7cb8859b4624..aa3978c88dc3 100644 --- a/private/react-native-fantom/runtime/setup.js +++ b/private/react-native-fantom/runtime/setup.js @@ -18,6 +18,7 @@ import type { } from './snapshotContext'; import {getConstants} from '../src/Constants'; +import createEach from './each'; import expect from './expect'; import {createMockFunction} from './mocks'; import patchWeakRef from './patchWeakRef'; @@ -205,6 +206,19 @@ global.it.skip = globalModifiers.pop(); }; +// $FlowExpectedError[prop-missing] +global.describe.each = createEach(global.describe); +// $FlowExpectedError[prop-missing] +global.describe.only.each = createEach(global.describe.only); +// $FlowExpectedError[prop-missing] +global.describe.skip.each = createEach(global.describe.skip); +// $FlowExpectedError[prop-missing] +global.it.each = createEach(global.it); +// $FlowExpectedError[prop-missing] +global.it.only.each = createEach(global.it.only); +// $FlowExpectedError[prop-missing] +global.it.skip.each = createEach(global.it.skip); + global.jest = { fn: createMockFunction, }; diff --git a/private/react-native-fantom/src/__tests__/setup/each-itest.js b/private/react-native-fantom/src/__tests__/setup/each-itest.js new file mode 100644 index 000000000000..3902f75ece78 --- /dev/null +++ b/private/react-native-fantom/src/__tests__/setup/each-itest.js @@ -0,0 +1,79 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import createEach from '../../../runtime/each'; + +const logs: Array = []; + +afterAll(() => { + expect(logs).toEqual([ + 'test 1 + 1 = 2', + 'test 2 + 3 = 5', + 'it 1', + 'it 2', + 'template 1 2', + 'describe first', + 'describe second', + ]); +}); + +test.each([ + [1, 1, 2], + [2, 3, 5], +])('%i + %i = %i', (a, b, sum) => { + logs.push(`test ${a} + ${b} = ${sum}`); +}); + +it.each([1, 2])('value %i', value => { + logs.push(`it ${value}`); +}); + +it.each` + value | doubled + ${1} | ${2} +`('doubles $value', ({value, doubled}) => { + logs.push(`template ${value} ${doubled}`); +}); + +describe.each([{name: 'first'}, {name: 'second'}])('$name', ({name}) => { + it('runs', () => { + logs.push(`describe ${name}`); + }); +}); + +function declareEmptyTable( + declare: (title: string, implementation: () => unknown) => void, +): void { + createEach(declare)([])('empty', () => {}); +} + +test('prints an object under %s with the toString its code defines, and otherwise as %p does', () => { + const titles: Array = []; + createEach(title => { + titles.push(title); + })([[{toString: () => 'defined'}, {a: 1}]])('%s %s', () => {}); + expect(titles).toEqual(['defined {"a": 1}']); +}); + +test('fails a table it cannot read with its message, from the function that declared it', () => { + let failingTest: () => unknown = () => {}; + declareEmptyTable((title, implementation) => { + failingTest = implementation; + }); + let thrown: unknown; + try { + failingTest(); + } catch (error: unknown) { + thrown = error; + } + expect(thrown instanceof Error ? thrown.stack : thrown).toMatch( + /^Error: Error: `\.each` called with an empty Array of table data\.\n+ +at declareEmptyTable\b/, + ); +});