summaryrefslogtreecommitdiff
path: root/tests/testdata/run/fix_worker_dispatchevent.ts
blob: 1b73b52dcbbdfc59678e72ea0cb4ec9ba1a25c47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const code = `
addEventListener("message", () => {
  postMessage("pong");
});

const context = new EventTarget();

Object.defineProperty(globalThis, "dispatchEvent", {
  value: context.dispatchEvent.bind(context),
  writable: true,
  enumerable: true,
  configurable: true,
});

postMessage("start");
`;

const blob = new Blob([code], { type: "application/javascript" });

const url = URL.createObjectURL(blob);

const worker = new Worker(url, { type: "module" });

let terminated = false;

worker.addEventListener("message", (evt) => {
  if (evt.data === "start") {
    worker.postMessage("ping");
  } else if (evt.data === "pong") {
    worker.terminate();
    terminated = true;
    console.log("success");
  } else {
    throw new Error("unexpected message from worker");
  }
});

setTimeout(() => {
  if (!terminated) {
    worker.terminate();
    throw new Error("did not receive message from worker in time");
  }
}, 2000);