GeezerVison is showing github.com — fix(jest-each): serialize bigint values in `%j` titles (#16338) · jestjs/jest@73f64cd
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: CHANGELOG.md +3Lines changed: 3 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| 22 | 22 | - `[@jest/transform]` Include the caller support flags in a transform's cache key, so a file transformed both as ESM and as CJS no longer serves one shape's output for the other ([#16331](https://github.com/jestjs/jest/pull/16331)) | 23 | 23 | - `[jest-config]` Add missing `findRelatedTests`, `outputFile`, and `replname` entries to `ValidConfig` so they no longer trigger spurious "Unknown option" warnings ([#16224](https://github.com/jestjs/jest/pull/16224)) | 24 | 24 | - `[jest-config]` Use `--config` for the global config when multiple `--projects` are specified ([#16273](https://github.com/jestjs/jest/pull/16273)) | | 25 | +- `[jest-core]` Serialize `bigint` values in `--json` and `--outputFile` output as their literal form (`4n`), instead of failing the run with `TypeError: Do not know how to serialize a BigInt` ([#16338](https://github.com/jestjs/jest/pull/16338)) | | 26 | +- `[jest-each]` Keep a `$&`, `` $` ``, `$'` or `$$` inside a `%p` param value out of the replacement, so the title shows the value instead of the text around it ([#16338](https://github.com/jestjs/jest/pull/16338)) | | 27 | +- `[jest-each]` Interpolate a `bigint` into a `%j` title as its literal form (`"4n"`) at any depth, instead of throwing `TypeError: Do not know how to serialize a BigInt` while collecting the tests ([#16338](https://github.com/jestjs/jest/pull/16338)) | 25 | 28 | - `[jest-environment-node, jest-util]` Only warn about a conflicting `globalsCleanup` mode when one was explicitly configured, and follow the mode that is actually in effect ([#16323](https://github.com/jestjs/jest/pull/16323)) | 26 | 29 | - `[jest-environment-node, jest-util]` Stop resolving lazy globals when setting up an environment, so Node 26's builtin module globals are no longer loaded (and no longer emit their deprecation warnings) for every test file ([#16324](https://github.com/jestjs/jest/pull/16324)) | 27 | 30 | - `[jest-haste-map]` Keep watch mode alive when an outside process briefly makes a file unreadable on Windows, instead of tearing the watcher down on `EPERM` ([#16295](https://github.com/jestjs/jest/pull/16295)) | |
Collapse file Copy file name to clipboard +51Lines changed: 51 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +/** | | 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. | | 3 | + * | | 4 | + * This source code is licensed under the MIT license found in the | | 5 | + * LICENSE file in the root directory of this source tree. | | 6 | + */ | | 7 | + | | 8 | +import {isJestJasmineRun} from '@jest/test-utils'; | | 9 | +import type {FormattedTestResults} from '@jest/test-result'; | | 10 | +import runJest from '../runJest'; | | 11 | + | | 12 | +it('reports bigint assertions without a serialization error', () => { | | 13 | + const {exitCode, stderr} = runJest('bigint'); | | 14 | + | | 15 | + expect(stderr).not.toContain('Do not know how to serialize a BigInt'); | | 16 | + expect(stderr).toContain('Expected: 10n'); | | 17 | + expect(stderr).toContain('Received: 4n'); | | 18 | + expect(stderr).toMatch(/1 failed, 2 passed/); | | 19 | + expect(exitCode).toBe(1); | | 20 | +}); | | 21 | + | | 22 | +it('interpolates bigints into an each title', () => { | | 23 | + const {exitCode, stderr} = runJest('bigint', [ | | 24 | + '--verbose', | | 25 | + '--testPathPatterns=each', | | 26 | + ]); | | 27 | + | | 28 | + expect(stderr).not.toContain('Do not know how to serialize a BigInt'); | | 29 | + expect(stderr).toContain('adds "1n" and "2n" to "3n"'); | | 30 | + expect(exitCode).toBe(0); | | 31 | +}); | | 32 | + | | 33 | +it('serializes bigint assertions to JSON', () => { | | 34 | + const {exitCode, stdout} = runJest('bigint', [ | | 35 | + '--json', | | 36 | + '--testPathPatterns=failing', | | 37 | + ]); | | 38 | + | | 39 | + expect(exitCode).toBe(1); | | 40 | + | | 41 | + const jsonResult: FormattedTestResults = JSON.parse(stdout); | | 42 | + | | 43 | + expect(jsonResult.numFailedTests).toBe(1); | | 44 | + | | 45 | + // jasmine2 fills `failureDetails` with its own result objects rather than | | 46 | + // `expect`'s `matcherResult`, so no bigint reaches the serializer there | | 47 | + if (!isJestJasmineRun()) { | | 48 | + expect(stdout).toContain('"actual":"4n"'); | | 49 | + expect(stdout).toContain('"expected":"10n"'); | | 50 | + } | | 51 | +}); |
Collapse file Copy file name to clipboard +14Lines changed: 14 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +/** | | 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. | | 3 | + * | | 4 | + * This source code is licensed under the MIT license found in the | | 5 | + * LICENSE file in the root directory of this source tree. | | 6 | + */ | | 7 | + | | 8 | +it.each([[1n, 2n, 3n]])('adds bigints', (a, b, expected) => { | | 9 | + expect(a + b).toBe(expected); | | 10 | +}); | | 11 | + | | 12 | +it.each([[1n, 2n, 3n]])('adds %j and %j to %j', (a, b, expected) => { | | 13 | + expect(a + b).toBe(expected); | | 14 | +}); |
Collapse file Copy file name to clipboard +10Lines changed: 10 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +/** | | 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. | | 3 | + * | | 4 | + * This source code is licensed under the MIT license found in the | | 5 | + * LICENSE file in the root directory of this source tree. | | 6 | + */ | | 7 | + | | 8 | +it('fails comparing bigints', () => { | | 9 | + expect(1n + 3n).toBe(10n); | | 10 | +}); |
Collapse file Copy file name to clipboard +5Lines changed: 5 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +{ | | 2 | + "jest": { | | 3 | + "testEnvironment": "node" | | 4 | + } | | 5 | +} |
Collapse file Copy file name to clipboardExpand all lines: packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts +17Lines changed: 17 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -26,6 +26,23 @@ it('serializes regular objects like JSON.stringify', () => { | 26 | 26 | expect(serializeToJSON(object)).toEqual(JSON.stringify(object)); | 27 | 27 | }); | 28 | 28 |
| | 29 | +it('serializes bigints', () => { | | 30 | + const objectWithBigInts = { | | 31 | + ...object, | | 32 | + matcherResult: {actual: 4n, expected: 10n}, | | 33 | + weight: -9n, | | 34 | + }; | | 35 | + | | 36 | + expect(() => JSON.stringify(objectWithBigInts)).toThrow( | | 37 | + 'Do not know how to serialize a BigInt', | | 38 | + ); | | 39 | + | | 40 | + expect(JSON.parse(serializeToJSON(objectWithBigInts))).toMatchObject({ | | 41 | + matcherResult: {actual: '4n', expected: '10n'}, | | 42 | + weight: '-9n', | | 43 | + }); | | 44 | +}); | | 45 | + | 29 | 46 | it('serializes errors', () => { | 30 | 47 | const objectWithError = { | 31 | 48 | ...object, | |
Collapse file Copy file name to clipboardExpand all lines: packages/jest-core/src/lib/serializeToJSON.ts +6-1Lines changed: 6 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -10,7 +10,8 @@ import {isError} from 'jest-util'; | 10 | 10 | /** | 11 | 11 | * When we're asked to give a JSON output with the --json flag or otherwise, | 12 | 12 | * some data we need to return don't serialize well with a basic | 13 | | - * `JSON.stringify`, particularly Errors returned in `.openHandles`. | | 13 | + * `JSON.stringify`, particularly Errors returned in `.openHandles` and BigInt | | 14 | + * values coming from assertions on `bigint`. | 14 | 15 | * | 15 | 16 | * This function handles the extended serialization wanted above. | 16 | 17 | */ | @@ -30,6 +31,10 @@ export default function serializeToJSON( | 30 | 31 | stack: value.stack, | 31 | 32 | }; | 32 | 33 | } | | 34 | + // JSON has no BigInt, so render it the way a JavaScript literal reads | | 35 | + if (typeof value === 'bigint') { | | 36 | + return `${value}n`; | | 37 | + } | 33 | 38 | return value; | 34 | 39 | }, | 35 | 40 | space, | |
Collapse file Copy file name to clipboardExpand all lines: packages/jest-each/src/__tests__/array.test.ts +48Lines changed: 48 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -166,6 +166,54 @@ describe('jest-each', () => { | 166 | 166 | ); | 167 | 167 | }); | 168 | 168 |
| | 169 | + test('calls global test with title containing bigint param values', () => { | | 170 | + const globalTestMocks = getGlobalTestMocks(); | | 171 | + const eachObject = each.withGlobal(globalTestMocks)([ | | 172 | + [1n, {nested: 2n}, [3n], -4n], | | 173 | + ]); | | 174 | + const testFunction = get(eachObject, keyPath); | | 175 | + testFunction('expected string: %j %j %j %s', noop); | | 176 | + | | 177 | + const globalMock = get(globalTestMocks, keyPath); | | 178 | + expect(globalMock).toHaveBeenCalledWith( | | 179 | + 'expected string: "1n" {"nested":"2n"} ["3n"] -4n', | | 180 | + expectFunction, | | 181 | + undefined, | | 182 | + ); | | 183 | + }); | | 184 | + | | 185 | + test('calls global test with title containing a cyclic %j param value', () => { | | 186 | + const cyclic: Record<string, unknown> = {}; | | 187 | + cyclic.self = cyclic; | | 188 | + const globalTestMocks = getGlobalTestMocks(); | | 189 | + const eachObject = each.withGlobal(globalTestMocks)([[cyclic]]); | | 190 | + const testFunction = get(eachObject, keyPath); | | 191 | + testFunction('expected string: %j', noop); | | 192 | + | | 193 | + const globalMock = get(globalTestMocks, keyPath); | | 194 | + expect(globalMock).toHaveBeenCalledWith( | | 195 | + 'expected string: [Circular]', | | 196 | + expectFunction, | | 197 | + undefined, | | 198 | + ); | | 199 | + }); | | 200 | + | | 201 | + test('calls global test with title containing param values holding replacement patterns', () => { | | 202 | + const globalTestMocks = getGlobalTestMocks(); | | 203 | + const eachObject = each.withGlobal(globalTestMocks)([ | | 204 | + ['$&', '$`', {nested: "$'"}], | | 205 | + ]); | | 206 | + const testFunction = get(eachObject, keyPath); | | 207 | + testFunction('expected string: %p %p %j', noop); | | 208 | + | | 209 | + const globalMock = get(globalTestMocks, keyPath); | | 210 | + expect(globalMock).toHaveBeenCalledWith( | | 211 | + `expected string: ${pretty('$&')} ${pretty('$`')} {"nested":"$'"}`, | | 212 | + expectFunction, | | 213 | + undefined, | | 214 | + ); | | 215 | + }); | | 216 | + | 169 | 217 | test('does not call global test with title containing more param values than sprintf placeholders', () => { | 170 | 218 | const globalTestMocks = getGlobalTestMocks(); | 171 | 219 | const eachObject = each.withGlobal(globalTestMocks)([ | |
Collapse file Copy file name to clipboardExpand all lines: packages/jest-each/src/table/array.ts +36-2Lines changed: 36 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -14,6 +14,7 @@ import {type Templates, interpolateVariables} from './interpolation'; | 14 | 14 |
| 15 | 15 | const SUPPORTED_PLACEHOLDERS = /%[#Odfijops]/g; | 16 | 16 | const PRETTY_PLACEHOLDER = '%p'; | | 17 | +const JSON_PLACEHOLDER = '%j'; | 17 | 18 | const INDEX_PLACEHOLDER = '%#'; | 18 | 19 | const NUMBER_PLACEHOLDER = '%$'; | 19 | 20 | const PLACEHOLDER_PREFIX = '%'; | @@ -70,6 +71,9 @@ const formatTitle = ( | 70 | 71 | if (placeholder === PRETTY_PLACEHOLDER) | 71 | 72 | return interpolatePrettyPlaceholder(formattedTitle, normalisedValue); | 72 | 73 |
| | 74 | + if (placeholder === JSON_PLACEHOLDER) | | 75 | + return interpolateJsonPlaceholder(formattedTitle, normalisedValue); | | 76 | + | 73 | 77 | return util.format(formattedTitle, normalisedValue); | 74 | 78 | }, | 75 | 79 | interpolateTitleIndexAndNumber( | @@ -95,5 +99,35 @@ const interpolateTitleIndexAndNumber = (title: string, index: number) => | 95 | 99 | .replace(INDEX_PLACEHOLDER, index.toString()) | 96 | 100 | .replace(NUMBER_PLACEHOLDER, (index + 1).toString()); | 97 | 101 |
| 98 | | -const interpolatePrettyPlaceholder = (title: string, value: unknown) => | 99 | | - title.replace(PRETTY_PLACEHOLDER, pretty(value, {maxDepth: 1, min: true})); | | 102 | +const interpolatePrettyPlaceholder = (title: string, value: unknown) => { | | 103 | + const prettyValue = pretty(value, {maxDepth: 1, min: true}); | | 104 | + return title.replace(PRETTY_PLACEHOLDER, () => prettyValue); | | 105 | +}; | | 106 | + | | 107 | +const interpolateJsonPlaceholder = (title: string, value: unknown) => { | | 108 | + const json = stringifyJson(value); | | 109 | + return title.replace(JSON_PLACEHOLDER, () => json); | | 110 | +}; | | 111 | + | | 112 | +// `util.format('%j', …)` throws on a `bigint`, so serialize here instead and | | 113 | +// render bigints the way a JavaScript literal reads. Cyclic values keep the | | 114 | +// `[Circular]` output `util.format` gives them. | | 115 | +function stringifyJson(value: unknown): string { | | 116 | + if (isCyclic(value)) { | | 117 | + return '[Circular]'; | | 118 | + } | | 119 | + return `${JSON.stringify(value, (_, entry) => | | 120 | + typeof entry === 'bigint' ? `${entry}n` : entry, | | 121 | + )}`; | | 122 | +} | | 123 | + | | 124 | +function isCyclic(value: unknown, ancestors: Array<unknown> = []): boolean { | | 125 | + if (value === null || typeof value !== 'object') { | | 126 | + return false; | | 127 | + } | | 128 | + if (ancestors.includes(value)) { | | 129 | + return true; | | 130 | + } | | 131 | + const nested = [...ancestors, value]; | | 132 | + return Object.values(value).some(entry => isCyclic(entry, nested)); | | 133 | +} |
|