diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fa452bf7523..29a0a980a16d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ - `[jest-transform]` Support transpiled transformers ([#11193](https://github.com/facebook/jest/pull/11193)) - `[jest-worker]` Add support for custom task queues and adds a `PriorityQueue` implementation. ([#10921](https://github.com/facebook/jest/pull/10921)) - `[jest-worker]` Add in-order scheduling policy to jest worker ([10902](https://github.com/facebook/jest/pull/10902)) +- `[pretty-format]` Better print for sparse arrays ([11326](https://github.com/facebook/jest/pull/11326)) ### Fixes diff --git a/packages/pretty-format/src/__tests__/prettyFormat.test.ts b/packages/pretty-format/src/__tests__/prettyFormat.test.ts index 9962cf4f4a0c..aa1e1f440542 100644 --- a/packages/pretty-format/src/__tests__/prettyFormat.test.ts +++ b/packages/pretty-format/src/__tests__/prettyFormat.test.ts @@ -41,6 +41,32 @@ describe('prettyFormat()', () => { expect(prettyFormat(val)).toEqual('Array [\n 1,\n 2,\n 3,\n]'); }); + it('prints a sparse array with only holes', () => { + // eslint-disable-next-line no-sparse-arrays + const val = [, , ,]; + expect(prettyFormat(val)).toEqual('Array [\n ,\n ,\n ,\n]'); + }); + + it('prints a sparse array with items', () => { + // eslint-disable-next-line no-sparse-arrays + const val = [1, , , 4]; + expect(prettyFormat(val)).toEqual('Array [\n 1,\n ,\n ,\n 4,\n]'); + }); + + it('prints a sparse array with value surrounded by holes', () => { + // eslint-disable-next-line no-sparse-arrays + const val = [, 5, ,]; + expect(prettyFormat(val)).toEqual('Array [\n ,\n 5,\n ,\n]'); + }); + + it('prints a sparse array also containing undefined values', () => { + // eslint-disable-next-line no-sparse-arrays + const val = [1, , undefined, undefined, , 4]; + expect(prettyFormat(val)).toEqual( + 'Array [\n 1,\n ,\n undefined,\n undefined,\n ,\n 4,\n]', + ); + }); + it('prints a empty typed array', () => { const val = new Uint32Array(0); expect(prettyFormat(val)).toEqual('Uint32Array []'); diff --git a/packages/pretty-format/src/collections.ts b/packages/pretty-format/src/collections.ts index 7876309e702b..6884059fe307 100644 --- a/packages/pretty-format/src/collections.ts +++ b/packages/pretty-format/src/collections.ts @@ -142,9 +142,11 @@ export function printListItems( const indentationNext = indentation + config.indent; for (let i = 0; i < list.length; i++) { - result += - indentationNext + - printer(list[i], config, indentationNext, depth, refs); + result += indentationNext; + + if (i in list) { + result += printer(list[i], config, indentationNext, depth, refs); + } if (i < list.length - 1) { result += ',' + config.spacingInner;