From 221e22b88250888d91d9deb2b1e24b22b6e9324d Mon Sep 17 00:00:00 2001 From: juandiegombr Date: Mon, 3 Jun 2024 16:02:56 +0200 Subject: [PATCH] fix: [#1429] Element.insertBefore works when the node is already inserted --- .../happy-dom/src/nodes/element/ElementUtility.ts | 4 ++++ .../happy-dom/test/nodes/element/Element.test.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/packages/happy-dom/src/nodes/element/ElementUtility.ts b/packages/happy-dom/src/nodes/element/ElementUtility.ts index bbb3368b9..e539b874a 100644 --- a/packages/happy-dom/src/nodes/element/ElementUtility.ts +++ b/packages/happy-dom/src/nodes/element/ElementUtility.ts @@ -137,6 +137,10 @@ export default class ElementUtility { referenceNode: Node | null, options?: { disableAncestorValidation?: boolean } ): Node { + if (newNode === referenceNode) { + return newNode; + } + // NodeUtility.insertBefore() will call appendChild() for the scenario where "referenceNode" is "null" or "undefined" if (newNode[PropertySymbol.nodeType] === NodeTypeEnum.elementNode && referenceNode) { if ( diff --git a/packages/happy-dom/test/nodes/element/Element.test.ts b/packages/happy-dom/test/nodes/element/Element.test.ts index 302f93cb8..0230cc9a2 100644 --- a/packages/happy-dom/test/nodes/element/Element.test.ts +++ b/packages/happy-dom/test/nodes/element/Element.test.ts @@ -1247,6 +1247,18 @@ describe('Element', () => { const elements = container.querySelectorAll('p'); expect(elements.length).toBe(1); }); + + it('Inserts correctly with when adding a children that is already inserted', () => { + const container = document.createElement('div'); + const child = document.createElement('p'); + child.textContent = 'A'; + container.appendChild(child); + + container.insertBefore(child, child); + + const elements = container.querySelectorAll('p'); + expect(elements.length).toBe(1); + }); }); describe('get previousElementSibling()', () => {