GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(jest-each): serialize bigint values in `%j` titles (#16338) · jestjs/jest@73f64cd

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • CHANGELOG.md
  • e2e
    • __tests__
      • bigint.test.ts
    • bigint
      • __tests__
        • each.test.js
        • failing.test.js
      • package.json
  • packages
    • jest-core/src/lib
      • __tests__
        • serializeToJSON.test.ts
      • serializeToJSON.ts
    • jest-each/src
      • __tests__
        • array.test.ts
      • table
        • array.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎CHANGELOG.md‎

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 numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
- `[@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))
2323
- `[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))
2424
- `[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))
2528
- `[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))
2629
- `[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))
2730
- `[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

‎e2e/__tests__/bigint.test.ts‎

Copy file name to clipboard
+51Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

‎e2e/bigint/__tests__/each.test.js‎

Copy file name to clipboard
+14Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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

‎e2e/bigint/__tests__/failing.test.js‎

Copy file name to clipboard
+10Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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

‎e2e/bigint/package.json‎

Copy file name to clipboard
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"jest": {
3+
"testEnvironment": "node"
4+
}
5+
}
Collapse file

‎packages/jest-core/src/lib/__tests__/serializeToJSON.test.ts‎

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 numberDiff line numberDiff line change
@@ -26,6 +26,23 @@ it('serializes regular objects like JSON.stringify', () => {
2626
expect(serializeToJSON(object)).toEqual(JSON.stringify(object));
2727
});
2828

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+
2946
it('serializes errors', () => {
3047
const objectWithError = {
3148
...object,
Collapse file

‎packages/jest-core/src/lib/serializeToJSON.ts‎

Copy file name to clipboardExpand all lines: packages/jest-core/src/lib/serializeToJSON.ts
+6-1Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import {isError} from 'jest-util';
1010
/**
1111
* When we're asked to give a JSON output with the --json flag or otherwise,
1212
* 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`.
1415
*
1516
* This function handles the extended serialization wanted above.
1617
*/
@@ -30,6 +31,10 @@ export default function serializeToJSON(
3031
stack: value.stack,
3132
};
3233
}
34+
// JSON has no BigInt, so render it the way a JavaScript literal reads
35+
if (typeof value === 'bigint') {
36+
return `${value}n`;
37+
}
3338
return value;
3439
},
3540
space,
Collapse file

‎packages/jest-each/src/__tests__/array.test.ts‎

Copy file name to clipboardExpand all lines: packages/jest-each/src/__tests__/array.test.ts
+48Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,54 @@ describe('jest-each', () => {
166166
);
167167
});
168168

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+
169217
test('does not call global test with title containing more param values than sprintf placeholders', () => {
170218
const globalTestMocks = getGlobalTestMocks();
171219
const eachObject = each.withGlobal(globalTestMocks)([
Collapse file

‎packages/jest-each/src/table/array.ts‎

Copy file name to clipboardExpand all lines: packages/jest-each/src/table/array.ts
+36-2Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {type Templates, interpolateVariables} from './interpolation';
1414

1515
const SUPPORTED_PLACEHOLDERS = /%[#Odfijops]/g;
1616
const PRETTY_PLACEHOLDER = '%p';
17+
const JSON_PLACEHOLDER = '%j';
1718
const INDEX_PLACEHOLDER = '%#';
1819
const NUMBER_PLACEHOLDER = '%$';
1920
const PLACEHOLDER_PREFIX = '%';
@@ -70,6 +71,9 @@ const formatTitle = (
7071
if (placeholder === PRETTY_PLACEHOLDER)
7172
return interpolatePrettyPlaceholder(formattedTitle, normalisedValue);
7273

74+
if (placeholder === JSON_PLACEHOLDER)
75+
return interpolateJsonPlaceholder(formattedTitle, normalisedValue);
76+
7377
return util.format(formattedTitle, normalisedValue);
7478
},
7579
interpolateTitleIndexAndNumber(
@@ -95,5 +99,35 @@ const interpolateTitleIndexAndNumber = (title: string, index: number) =>
9599
.replace(INDEX_PLACEHOLDER, index.toString())
96100
.replace(NUMBER_PLACEHOLDER, (index + 1).toString());
97101

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+
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.