Skip to content

Commit

Permalink
Merge pull request #54 from bfanger/fix-portal-not-removed
Browse files Browse the repository at this point in the history
fix: Remove element based on component lifecycle
  • Loading branch information
romkor authored Mar 29, 2021
2 parents d8bebee + 5e6032b commit 4515cb4
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/Portal.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@
}
function destroy() {
if (el.parent) {
el.parent.removeChild(el);
if (el.parentNode) {
el.parentNode.removeChild(el);
}
}
Expand Down
35 changes: 34 additions & 1 deletion test/Portal.test.js
Original file line number Diff line number Diff line change
@@ -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("<Portal />", () => {
describe("<Portal /> target", () => {
let wrapper;

beforeEach(() => {
Expand Down Expand Up @@ -42,3 +44,34 @@ describe("<Portal />", () => {
expect(isPortalContainerEmpty).toBe(true);
});
});

describe("<Portal /> 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);
});
});
18 changes: 18 additions & 0 deletions test/TestLifecycle.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<script>
import { fade } from "svelte/transition";
import Portal from "../src/Portal.svelte";
export let modalVisible = true;
export let containerVisible = true;
</script>

{#if containerVisible}
<div out:fade={{ duration: 100 }} on:outroend>
{#if modalVisible}
<Portal target="#modals">
<div id="modal" />
</Portal>
{/if}
</div>
{/if}
<div id="modals" />

0 comments on commit 4515cb4

Please sign in to comment.