Skip to content

Commit eb4c0ab

Browse files
pedrottimarkcpojer
authored andcommitted
Sort attributes by name in HTMLElement plugin (#3783)
1 parent 1199558 commit eb4c0ab

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

packages/pretty-format/src/__tests__/html_element.test.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,11 @@ describe('HTMLElement Plugin', () => {
4646

4747
it('supports an HTML element with multiple attributes', () => {
4848
const parent = document.createElement('div');
49+
// set attributes in unsorted order by name to verify sorting
4950
parent.setAttribute('id', 123);
5051
parent.setAttribute('class', 'classy');
5152

52-
expect(parent).toPrettyPrintTo('<div\n id="123"\n class="classy"\n/>');
53+
expect(parent).toPrettyPrintTo('<div\n class="classy"\n id="123"\n/>');
5354
});
5455

5556
it('supports an element with text content', () => {
@@ -71,11 +72,12 @@ describe('HTMLElement Plugin', () => {
7172
const child = document.createElement('span');
7273
parent.appendChild(child);
7374

74-
child.setAttribute('id', 123);
75+
// set attributes in sorted order by name
7576
child.setAttribute('class', 'classy');
77+
child.setAttribute('id', 123);
7678

7779
expect(parent).toPrettyPrintTo(
78-
'<div>\n <span\n id="123"\n class="classy"\n />\n</div>',
80+
'<div>\n <span\n class="classy"\n id="123"\n />\n</div>',
7981
);
8082
});
8183

packages/pretty-format/src/plugins/html_element.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,12 @@ function printChildren(flatChildren, print, indent, colors, opts) {
6363

6464
function printAttributes(attributes: Array<Attribute>, indent, colors, opts) {
6565
return attributes
66-
.sort()
66+
.sort(
67+
(attributeA, attributeB) =>
68+
attributeA.name === attributeB.name
69+
? 0
70+
: attributeA.name < attributeB.name ? -1 : 1,
71+
)
6772
.map(attribute => {
6873
return (
6974
opts.spacing +

0 commit comments

Comments
 (0)