fix(websocket): pass through underlying WebSocket protocol (#33446)

This commit is contained in:
Max Schmitt 2024-11-05 11:13:33 +01:00 committed by GitHub
parent 8e140a4873
commit 9a668aeab3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 4 deletions

View File

@ -331,6 +331,13 @@ export function inject(globalThis: GlobalThis) {
_ensureOpened() {
if (this.readyState !== WebSocketMock.CONNECTING)
return;
this.extensions = this._ws?.extensions || '';
if (this._ws)
this.protocol = this._ws.protocol;
else if (Array.isArray(this._protocols))
this.protocol = this._protocols[0] || '';
else
this.protocol = this._protocols || '';
this.readyState = WebSocketMock.OPEN;
this.dispatchEvent(new Event('open', { cancelable: true }));
}

View File

@ -33,11 +33,11 @@ function withResolvers<T = void>() {
return { promise, resolve };
}
async function setupWS(target: Page | Frame, port: number, binaryType: 'blob' | 'arraybuffer') {
async function setupWS(target: Page | Frame, port: number, binaryType: 'blob' | 'arraybuffer', protocols?: string | string[]) {
await target.goto('about:blank');
await target.evaluate(({ port, binaryType }) => {
await target.evaluate(({ port, binaryType, protocols }) => {
window.log = [];
window.ws = new WebSocket('ws://localhost:' + port + '/ws');
window.ws = new WebSocket('ws://localhost:' + port + '/ws', protocols);
window.ws.binaryType = binaryType;
window.ws.addEventListener('open', () => window.log.push('open'));
window.ws.addEventListener('close', event => window.log.push(`close code=${event.code} reason=${event.reason} wasClean=${event.wasClean}`));
@ -53,7 +53,7 @@ async function setupWS(target: Page | Frame, port: number, binaryType: 'blob' |
window.log.push(`message: data=${data} origin=${event.origin} lastEventId=${event.lastEventId}`);
});
window.wsOpened = new Promise(f => window.ws.addEventListener('open', () => f()));
}, { port, binaryType });
}, { port, binaryType, protocols });
}
for (const mock of ['no-mock', 'no-match', 'pass-through']) {
@ -191,6 +191,13 @@ for (const mock of ['no-mock', 'no-match', 'pass-through']) {
expect(closed.code).toBe(3002);
expect(closed.reason.toString()).toBe('oops');
});
test('should pass through the required protocol', async ({ page, server }) => {
await setupWS(page, server.PORT, 'blob', 'my-custom-protocol');
await page.evaluate(() => window.wsOpened);
const protocol = await page.evaluate(() => window.ws.protocol);
expect(protocol).toBe('my-custom-protocol');
});
});
}