0
Fork 0
mirror of https://github.com/penpot/penpot.git synced 2025-01-09 16:30:37 -05:00
penpot/frontend/playwright/helpers/MockWebSocketHelper.js

95 lines
2.6 KiB
JavaScript
Raw Normal View History

2024-05-07 06:12:58 -05:00
export class MockWebSocketHelper extends EventTarget {
2024-05-07 04:18:35 -05:00
static #mocks = new Map();
2024-04-25 07:14:46 -05:00
static async init(page) {
this.#mocks = new Map();
await page.exposeFunction("onMockWebSocketConstructor", (url) => {
const webSocket = new MockWebSocketHelper(page, url);
2024-05-07 04:18:35 -05:00
this.#mocks.set(url, webSocket);
});
await page.exposeFunction("onMockWebSocketSpyMessage", (url, data) => {
2024-05-07 06:12:58 -05:00
if (!this.#mocks.has(url)) {
throw new Error(`WebSocket with URL ${url} not found`);
}
2024-05-07 04:18:35 -05:00
this.#mocks.get(url).dispatchEvent(new MessageEvent("message", { data }));
});
2024-07-01 03:28:40 -05:00
await page.exposeFunction(
"onMockWebSocketSpyClose",
(url, code, reason) => {
if (!this.#mocks.has(url)) {
throw new Error(`WebSocket with URL ${url} not found`);
}
this.#mocks
.get(url)
.dispatchEvent(new CloseEvent("close", { code, reason }));
},
);
2024-04-25 07:14:46 -05:00
await page.addInitScript({ path: "playwright/scripts/MockWebSocket.js" });
}
2024-05-07 04:18:35 -05:00
static waitForURL(url) {
return new Promise((resolve) => {
const intervalID = setInterval(() => {
for (const [wsURL, ws] of this.#mocks) {
if (wsURL.includes(url)) {
clearInterval(intervalID);
return resolve(ws);
}
}
}, 30);
});
}
#page = null;
#url;
constructor(page, url, protocols) {
super();
this.#page = page;
this.#url = url;
}
mockOpen(options) {
return this.#page.evaluate(
({ url, options }) => {
if (typeof WebSocket.getByURL !== "function") {
throw new Error(
"WebSocket.getByURL is not a function. Did you forget to call MockWebSocket.init(page)?",
);
}
WebSocket.getByURL(url).mockOpen(options);
},
{ url: this.#url, options },
);
2024-05-07 04:18:35 -05:00
}
mockMessage(data) {
return this.#page.evaluate(
({ url, data }) => {
if (typeof WebSocket.getByURL !== "function") {
throw new Error(
"WebSocket.getByURL is not a function. Did you forget to call MockWebSocket.init(page)?",
);
}
WebSocket.getByURL(url).mockMessage(data);
},
{ url: this.#url, data },
);
2024-05-07 04:18:35 -05:00
}
mockClose() {
return this.#page.evaluate(
({ url }) => {
if (typeof WebSocket.getByURL !== "function") {
throw new Error(
"WebSocket.getByURL is not a function. Did you forget to call MockWebSocket.init(page)?",
);
}
WebSocket.getByURL(url).mockClose();
},
{ url: this.#url },
);
2024-05-07 04:18:35 -05:00
}
2024-04-25 07:14:46 -05:00
}