From 3bc8acb8c364691fa958613ae7dfeac3fae3f08a Mon Sep 17 00:00:00 2001 From: Benjamin Seber Date: Fri, 25 Oct 2024 14:00:15 +0200 Subject: [PATCH] add tooltip test --- .../components/tooltip/tooltip.spec.ts | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 src/main/javascript/components/tooltip/tooltip.spec.ts diff --git a/src/main/javascript/components/tooltip/tooltip.spec.ts b/src/main/javascript/components/tooltip/tooltip.spec.ts new file mode 100644 index 00000000..5138fa38 --- /dev/null +++ b/src/main/javascript/components/tooltip/tooltip.spec.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { Tooltip } from "./tooltip"; +import * as popper from "@popperjs/core"; + +vi.spyOn(popper, "createPopper"); + +describe("tooltip", () => { + afterEach(() => { + while (document.body.firstChild) { + document.body.firstChild.remove(); + } + }); + + test("sets role attribute", () => { + document.body.innerHTML = '
'; + + const paragraph = document.createElement("p"); + paragraph.textContent = "tooltip text"; + + const tooltip = new Tooltip(); + expect(tooltip.getAttribute("role")).toBe("tooltip"); + }); + + test("initializes tooltip on mount", () => { + document.body.innerHTML = '
'; + const tooltip = anyTooltip(); + + expect(popper.createPopper).not.toHaveBeenCalled(); + + document.querySelector("#parent").append(tooltip); + expect(popper.createPopper).toHaveBeenCalled(); + }); + + test.each([["mouseenter"], ["focus"]])("shows tooltip on %s", (eventName) => { + const popperInstance = { + update: vi.fn(), + }; + vi.mocked(popper.createPopper).mockReturnValue(popperInstance); + + document.body.innerHTML = '
'; + const root = document.querySelector("#parent"); + const tooltip = anyTooltip(); + root.append(tooltip); + + expect(tooltip.dataset.show).not.toBeDefined(); + + root.dispatchEvent(new Event(eventName)); + expect(tooltip.dataset.show).toBeDefined(); + expect(popperInstance.update).toHaveBeenCalledOnce(); + }); + + test.each([["mouseleave"], ["blur"]])("hides tooltip on %s", (eventName) => { + document.body.innerHTML = '
'; + const root = document.querySelector("#parent"); + const tooltip = anyTooltip(); + root.append(tooltip); + + tooltip.dataset.show = ""; + + root.dispatchEvent(new Event(eventName)); + expect(tooltip.dataset.show).not.toBeDefined(); + }); +}); + +function anyTooltip() { + const paragraph = document.createElement("p"); + paragraph.textContent = "tooltip text"; + + const tooltip = new Tooltip(); + tooltip.append(paragraph); + + return tooltip; +}