From 3d7ef3c0624f9b4f3a5fc3077bf01cf168d81dbc Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Tue, 15 Oct 2024 04:56:29 -0700 Subject: [PATCH] cherry-pick(#33095): fix(routeWebSocket): make sure ws url without trailing slash is supported (#33112) --- .../src/server/injected/webSocketMock.ts | 1 + tests/library/route-web-socket.spec.ts | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/packages/playwright-core/src/server/injected/webSocketMock.ts b/packages/playwright-core/src/server/injected/webSocketMock.ts index 69d6bc0585994..7a4742bac3085 100644 --- a/packages/playwright-core/src/server/injected/webSocketMock.ts +++ b/packages/playwright-core/src/server/injected/webSocketMock.ts @@ -143,6 +143,7 @@ export function inject(globalThis: GlobalThis) { this.url = typeof url === 'string' ? url : url.href; try { + this.url = new URL(url).href; this._origin = new URL(url).origin; } catch { } diff --git a/tests/library/route-web-socket.spec.ts b/tests/library/route-web-socket.spec.ts index 46a75cdefb339..6af0cb4bc0a0d 100644 --- a/tests/library/route-web-socket.spec.ts +++ b/tests/library/route-web-socket.spec.ts @@ -508,3 +508,27 @@ test('should throw when connecting twice', async ({ page, server }) => { const error = await promise; expect(error.message).toContain('Already connected to the server'); }); + +test('should work with no trailing slash', async ({ page, server }) => { + const log: string[] = []; + // No trailing slash! + await page.routeWebSocket('ws://localhost:' + server.PORT, ws => { + ws.onMessage(message => { + log.push(message as string); + ws.send('response'); + }); + }); + + await page.goto('about:blank'); + await page.evaluate(({ port }) => { + window.log = []; + // No trailing slash! + window.ws = new WebSocket('ws://localhost:' + port); + window.ws.addEventListener('message', event => window.log.push(event.data)); + }, { port: server.PORT }); + + await expect.poll(() => page.evaluate(() => window.ws.readyState)).toBe(1); + await page.evaluate(() => window.ws.send('query')); + await expect.poll(() => log).toEqual(['query']); + expect(await page.evaluate(() => window.log)).toEqual(['response']); +});