|
1 | | -import { it, expect, suite, assert } from "vitest"; |
2 | | -import { render, screen, act, cleanup, within } from "@testing-library/preact"; |
| 1 | +import { it, expect, suite, assert, vi } from "vitest"; |
| 2 | +import { |
| 3 | + render, |
| 4 | + screen, |
| 5 | + act, |
| 6 | + cleanup, |
| 7 | + waitFor, |
| 8 | + within, |
| 9 | +} from "@testing-library/preact"; |
3 | 10 | import { CodeFrame } from "@components/CodeEmbed/frame"; |
| 11 | +import { cdnLibraryUrl } from "@/src/globals/globals"; |
4 | 12 |
|
5 | 13 | suite("CodeFrame", () => { |
6 | 14 | it("defaults to empty DOM", async () => { |
@@ -30,4 +38,65 @@ suite("CodeFrame", () => { |
30 | 38 |
|
31 | 39 | cleanup(); |
32 | 40 | }); |
| 41 | + |
| 42 | + it("only sends the p5 script to its own iframe origin", async () => { |
| 43 | + const postMessage = vi.fn(); |
| 44 | + const contentWindowSpy = vi |
| 45 | + .spyOn(HTMLIFrameElement.prototype, "contentWindow", "get") |
| 46 | + .mockReturnValue({ postMessage } as unknown as Window); |
| 47 | + class ImmediateIntersectionObserver { |
| 48 | + private callback: IntersectionObserverCallback; |
| 49 | + |
| 50 | + constructor(callback: IntersectionObserverCallback) { |
| 51 | + this.callback = callback; |
| 52 | + } |
| 53 | + |
| 54 | + observe() { |
| 55 | + this.callback( |
| 56 | + [{ isIntersecting: true } as IntersectionObserverEntry], |
| 57 | + this as unknown as IntersectionObserver, |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + disconnect() {} |
| 62 | + } |
| 63 | + vi.stubGlobal("IntersectionObserver", ImmediateIntersectionObserver); |
| 64 | + vi.stubGlobal( |
| 65 | + "fetch", |
| 66 | + vi.fn().mockResolvedValue({ text: () => Promise.resolve("p5 source") }), |
| 67 | + ); |
| 68 | + const p5Script = document.createElement("script"); |
| 69 | + p5Script.id = "p5ScriptTag"; |
| 70 | + p5Script.src = "/p5.min.js"; |
| 71 | + document.body.appendChild(p5Script); |
| 72 | + |
| 73 | + try { |
| 74 | + act(() => { |
| 75 | + render(<CodeFrame jsCode="function setup() {}" />); |
| 76 | + }); |
| 77 | + |
| 78 | + const frame = screen.getByTitle("Code Preview") as HTMLIFrameElement; |
| 79 | + |
| 80 | + await waitFor(() => |
| 81 | + expect(postMessage).toHaveBeenCalledWith( |
| 82 | + { |
| 83 | + sender: cdnLibraryUrl, |
| 84 | + message: "p5 source", |
| 85 | + }, |
| 86 | + window.location.origin, |
| 87 | + ), |
| 88 | + ); |
| 89 | + expect(frame.srcdoc).toContain( |
| 90 | + `if (event.origin !== '${window.location.origin}') return;`, |
| 91 | + ); |
| 92 | + expect(frame.srcdoc).toContain( |
| 93 | + "if (event.source !== window.parent) return;", |
| 94 | + ); |
| 95 | + } finally { |
| 96 | + cleanup(); |
| 97 | + p5Script.remove(); |
| 98 | + contentWindowSpy.mockRestore(); |
| 99 | + vi.unstubAllGlobals(); |
| 100 | + } |
| 101 | + }); |
33 | 102 | }); |
0 commit comments