Skip to content

Commit

Permalink
fix(serializers): generated id="root{n}" should be removed
Browse files Browse the repository at this point in the history
BREAKING CHANGE

This change will affect snapshot generation. One should update component snapshots via `-u` Jest CLI option. Since this change only removes the root `id`, it shouldn't affect the quality of snapshots in general.
  • Loading branch information
wellwind authored and ahnpnl committed Feb 27, 2025
1 parent 41cb645 commit 3749c78
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ exports[`FooComponent should allow generating snapshot 1`] = `
>
<p>
Line 1
</p><div>
</p><div
id="foo"
>
<div>
val1
</div>
Expand All @@ -18,13 +20,13 @@ exports[`FooComponent should allow generating snapshot 1`] = `
`;

exports[`FooComponent should allow generating snapshot 2`] = `
<div
id="root1"
>
<div>
<p>
Line 1
</p>
<div>
<div
id="foo"
>
<div>
val1
</div>
Expand All @@ -38,7 +40,9 @@ exports[`FooComponent should allow generating snapshot with removed component at
<foo>
<p>
Line 1
</p><div>
</p><div
id="foo"
>
<div>
val1
</div>
Expand All @@ -47,13 +51,13 @@ exports[`FooComponent should allow generating snapshot with removed component at
`;

exports[`FooComponent should allow generating snapshot with removed component attributes with snapshot serializer option 2`] = `
<div
id="root0"
>
<div>
<p>
Line 1
</p>
<div>
<div
id="foo"
>
<div>
val1
</div>
Expand Down
3 changes: 2 additions & 1 deletion e2e/snapshot-serializers/foo.component.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<!-- SOMETHING -->
<p>Line 1</p>
<div>
<div id="foo">
<!-- this id attribute should not be eliminate -->
<div *ngIf="condition1">
{{ value1() }}
</div>
Expand Down
9 changes: 9 additions & 0 deletions src/serializers/no-ng-attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ const hasAttributesToClean = (attribute: Attr): boolean =>

const removeAngularAttributes = (node: Element): Element => {
const nodeCopy = node.cloneNode(true) as Element;
// if parent of original node is body,
// means the node is additionally generated when call TestBed.createComponent,
// this node will have id="root{n}", will cause snapshot testing not stable,
// so the id attribute should be removed
if (node.parentElement?.tagName === 'BODY') {
nodeCopy.removeAttribute('id');
}

// Remove angular-specific attributes
Object.values(nodeCopy.attributes)
.filter(hasAttributesToRemove)
.forEach((attribute) => nodeCopy.attributes.removeNamedItem(attribute.name));
Expand Down

0 comments on commit 3749c78

Please sign in to comment.