toastAnchorFallback.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // @vitest-environment jsdom
  2. import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
  3. import { createElement } from "react";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. AnchoredToastStack,
  7. type ToastItem,
  8. } from "@/components/ui/toast.js";
  9. function createItem(id: number, message: string): ToastItem {
  10. return {
  11. id,
  12. message,
  13. durationMs: 0,
  14. position: "top-center",
  15. anchorId: "automations-main-toast-anchor",
  16. };
  17. }
  18. afterEach(() => {
  19. vi.useRealTimers();
  20. cleanup();
  21. document.body.replaceChildren();
  22. });
  23. describe("AnchoredToastStack", () => {
  24. it("falls back to viewport center when the anchor is missing", () => {
  25. const { container } = render(
  26. createElement(AnchoredToastStack, {
  27. anchorId: "automations-main-toast-anchor",
  28. items: [createItem(1, "fallback toast")],
  29. onDone: vi.fn(),
  30. }),
  31. );
  32. expect(screen.getByText("fallback toast")).toBeTruthy();
  33. expect(container.firstElementChild?.className).toContain("left-1/2");
  34. });
  35. it("still expires when the anchor is missing", () => {
  36. vi.useFakeTimers();
  37. const onDone = vi.fn();
  38. const item = { ...createItem(3, "expiring toast"), durationMs: 10 };
  39. render(
  40. createElement(AnchoredToastStack, {
  41. anchorId: "automations-main-toast-anchor",
  42. items: [item],
  43. onDone,
  44. }),
  45. );
  46. act(() => vi.advanceTimersByTime(210));
  47. expect(onDone).toHaveBeenCalledWith(3);
  48. });
  49. it("falls back to viewport center when the anchor unmounts", async () => {
  50. const anchor = document.createElement("main");
  51. anchor.id = "automations-main-toast-anchor";
  52. anchor.getBoundingClientRect = () =>
  53. ({ left: 240, width: 960 }) as DOMRect;
  54. document.body.appendChild(anchor);
  55. const { container } = render(
  56. createElement(AnchoredToastStack, {
  57. anchorId: "automations-main-toast-anchor",
  58. items: [createItem(2, "moving toast")],
  59. onDone: vi.fn(),
  60. }),
  61. );
  62. await waitFor(() => {
  63. expect((container.firstElementChild as HTMLElement).style.left).toBe("720px");
  64. });
  65. anchor.remove();
  66. await waitFor(() => {
  67. expect(container.firstElementChild?.className).toContain("left-1/2");
  68. });
  69. expect(screen.getByText("moving toast")).toBeTruthy();
  70. });
  71. });