From b5a853e574ff80f65bb50fe38d89352359f92141 Mon Sep 17 00:00:00 2001 From: Agata Szczuka Date: Wed, 28 Jun 2023 17:20:08 +0200 Subject: [PATCH] Issue-1213: Fix accessing nextSibling property in insertNodeAt function. --- src/util/helper.js | 2 +- tests/unit/util/helper.spec.js | 27 +++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/util/helper.js b/src/util/helper.js index 37bf9e09..b1f30d6c 100644 --- a/src/util/helper.js +++ b/src/util/helper.js @@ -29,7 +29,7 @@ function insertNodeAt(fatherNode, node, position) { const refNode = position === 0 ? fatherNode.children[0] - : fatherNode.children[position - 1].nextSibling; + : fatherNode.children[position - 1]?.nextSibling; fatherNode.insertBefore(node, refNode); } diff --git a/tests/unit/util/helper.spec.js b/tests/unit/util/helper.spec.js index 4f9daa48..4494cbad 100644 --- a/tests/unit/util/helper.spec.js +++ b/tests/unit/util/helper.spec.js @@ -1,4 +1,4 @@ -import { camelize, console } from "@/util/helper"; +import { camelize, console, insertNodeAt } from "@/util/helper"; describe("camelize", () => { test.each([ @@ -30,4 +30,27 @@ describe("console", () => { expect(typeof actual).toEqual("function"); } ) -}); \ No newline at end of file +}); + +describe('insertNodeAt', () => { + const node = document.createElement('div'); + const nextSibling = document.createElement('div'); + const child = { nextSibling }; + const mockInsertBefore = jest.fn(); + const fatherNode = { + insertBefore: mockInsertBefore, + children: [child] + } + test('Inserts node at 0 position', () => { + insertNodeAt(fatherNode, node, 0); + expect(mockInsertBefore).toHaveBeenCalledWith(node, child); + }) + test('Inserts node at 1 position', () => { + insertNodeAt(fatherNode, node, 1); + expect(mockInsertBefore).toHaveBeenCalledWith(node, nextSibling); + }) + test("Inserts node at the end of node's child nodes", () => { + insertNodeAt(fatherNode, node, 2); + expect(mockInsertBefore).toHaveBeenCalledWith(node, undefined); + }) +});