Skip to content

Commit

Permalink
fix(pretty-format): print ArrayBuffer and DataView correctly (#14290)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing authored Sep 20, 2023
1 parent 571b230 commit c13c649
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

- `[babel-plugin-jest-hoist]` Use `denylist` instead of the deprecated `blacklist` for Babel 8 support ([#14109](https://github.com/jestjs/jest/pull/14109))
- `[jest-leak-detector]` Make leak-detector more aggressive when running GC ([#14526](https://github.com/jestjs/jest/pull/14526))
- `[pretty-format]` [**BREAKING**] Print `ArrayBuffer` and `DataView` correctly ([#14290](https://github.com/facebook/jest/pull/14290))

### Performance

Expand Down
7 changes: 6 additions & 1 deletion packages/pretty-format/src/__tests__/prettyFormat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,12 @@ describe('prettyFormat()', () => {

it('prints an array buffer', () => {
const val = new ArrayBuffer(3);
expect(prettyFormat(val)).toBe('ArrayBuffer []');
expect(prettyFormat(val)).toBe('ArrayBuffer [\n 0,\n 0,\n 0,\n]');
});

it('prints an data view', () => {
const val = new DataView(new ArrayBuffer(3));
expect(prettyFormat(val)).toBe('DataView [\n 0,\n 0,\n 0,\n]');
});

it('prints a nested array', () => {
Expand Down
21 changes: 15 additions & 6 deletions packages/pretty-format/src/collections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,33 +146,42 @@ export function printIteratorValues(
* without surrounding punctuation (for example, brackets)
**/
export function printListItems(
list: ArrayLike<unknown>,
list: ArrayLike<unknown> | DataView | ArrayBuffer,
config: Config,
indentation: string,
depth: number,
refs: Refs,
printer: Printer,
): string {
let result = '';
list = list instanceof ArrayBuffer ? new DataView(list) : list;
const isDataView = (l: unknown): l is DataView => l instanceof DataView;
const length = isDataView(list) ? list.byteLength : list.length;

if (list.length > 0) {
if (length > 0) {
result += config.spacingOuter;

const indentationNext = indentation + config.indent;

for (let i = 0; i < list.length; i++) {
for (let i = 0; i < length; i++) {
result += indentationNext;

if (i === config.maxWidth) {
result += '…';
break;
}

if (i in list) {
result += printer(list[i], config, indentationNext, depth, refs);
if (isDataView(list) || i in list) {
result += printer(
isDataView(list) ? list.getInt8(i) : list[i],
config,
indentationNext,
depth,
refs,
);
}

if (i < list.length - 1) {
if (i < length - 1) {
result += `,${config.spacingInner}`;
} else if (!config.min) {
result += ',';
Expand Down

0 comments on commit c13c649

Please sign in to comment.