From 5e6032b3a6f4d54ef24477421eda23dc8f68f8fb Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Sat, 27 Mar 2021 07:04:56 +0100 Subject: [PATCH] fix: Remove element based on component lifecycle --- src/Portal.svelte | 4 ++-- test/Portal.test.js | 35 ++++++++++++++++++++++++++++++++++- test/TestLifecycle.svelte | 18 ++++++++++++++++++ 3 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 test/TestLifecycle.svelte diff --git a/src/Portal.svelte b/src/Portal.svelte index 6c85cb8..510a1a5 100644 --- a/src/Portal.svelte +++ b/src/Portal.svelte @@ -36,8 +36,8 @@ } function destroy() { - if (el.parent) { - el.parent.removeChild(el); + if (el.parentNode) { + el.parentNode.removeChild(el); } } diff --git a/test/Portal.test.js b/test/Portal.test.js index 0b5f5d5..2a840fc 100644 --- a/test/Portal.test.js +++ b/test/Portal.test.js @@ -1,8 +1,10 @@ import { render } from "@testing-library/svelte"; import TestPortalWrapper from "./TestPortalWrapper.svelte"; +import TestLifecycle from "./TestLifecycle.svelte"; +import { tick } from "svelte"; -describe("", () => { +describe(" target", () => { let wrapper; beforeEach(() => { @@ -42,3 +44,34 @@ describe("", () => { expect(isPortalContainerEmpty).toBe(true); }); }); + +describe(" lifecycle", () => { + let targetEl; + let lifecycleComponent; + beforeEach(() => { + let { container, component } = render(TestLifecycle); + lifecycleComponent = component; + targetEl = container.querySelector("#modals"); + }); + it("should be added and removed from dom", async () => { + expect(targetEl.children).toHaveLength(1); + lifecycleComponent.$set({ modalVisible: false }); + await tick(); + expect(targetEl.children).toHaveLength(0); + lifecycleComponent.$set({ modalVisible: true }); + await tick(); + expect(targetEl.children).toHaveLength(1); + }); + it("should be removed from dom after after outro", async () => { + lifecycleComponent.$set({ containerVisible: false }); + await tick(); + expect(targetEl.children).toHaveLength(1); + await new Promise((resolve) => { + const unsubscribe = lifecycleComponent.$on("outroend", () => { + resolve(); + unsubscribe(); + }); + }); + expect(targetEl.children).toHaveLength(0); + }); +}); diff --git a/test/TestLifecycle.svelte b/test/TestLifecycle.svelte new file mode 100644 index 0000000..956465c --- /dev/null +++ b/test/TestLifecycle.svelte @@ -0,0 +1,18 @@ + + +{#if containerVisible} +
+ {#if modalVisible} + + +{/if} +