Skip to content

Commit

Permalink
fix(client): Return ping's payload through the response pong
Browse files Browse the repository at this point in the history
  • Loading branch information
enisdenjo committed Jun 9, 2021
1 parent e2c8f67 commit ee6193a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 5 deletions.
16 changes: 14 additions & 2 deletions src/client.ts
Expand Up @@ -559,8 +559,20 @@ export function createClient(options: ClientOptions): Client {
enqueuePing(); // enqueue next ping (noop if disabled)
} else if (!disablePong) {
// respond with pong on ping
socket.send(stringifyMessage({ type: MessageType.Pong }));
emitter.emit('pong', false, undefined);
socket.send(
stringifyMessage(
message.payload
? {
type: MessageType.Pong,
payload: message.payload,
}
: {
type: MessageType.Pong,
// payload is completely absent if not provided
},
),
);
emitter.emit('pong', false, message.payload);
}
return; // ping and pongs can be received whenever
}
Expand Down
46 changes: 43 additions & 3 deletions src/tests/client.ts
Expand Up @@ -5,7 +5,12 @@
import WebSocket from 'ws';
import { EventEmitter } from 'events';
import { createClient, Client, EventListener } from '../client';
import { MessageType, stringifyMessage, SubscribePayload } from '../common';
import {
MessageType,
parseMessage,
stringifyMessage,
SubscribePayload,
} from '../common';
import { startWSTServer as startTServer, waitForDone } from './utils';

// simulate browser environment for easier client testing
Expand Down Expand Up @@ -429,6 +434,41 @@ describe('ping/pong', () => {
}, 20);
});

it("should return ping's payload through the pong", async () => {
expect.assertions(1);

const { url, waitForConnect, waitForClient, waitForClientClose } =
await startTServer();

createClient({
url,
lazy: false,
retryAttempts: 0,
onNonLazyError: noop,
});

await waitForConnect();

await waitForClient((client) => {
client.send(
stringifyMessage({
type: MessageType.Ping,
payload: { iCome: 'back' },
}),
);
client.onMessage((data) => {
expect(parseMessage(data)).toEqual({
type: MessageType.Pong,
payload: { iCome: 'back' },
});
});
});

await waitForClientClose(() => {
fail("Shouldn't have closed");
}, 20);
});

it('should not respond with a pong to a ping when disabled', async () => {
const { url, waitForConnect, waitForClient, waitForClientClose } =
await startTServer();
Expand Down Expand Up @@ -1670,8 +1710,8 @@ describe('events', () => {

expect(pongFn).toBeCalledTimes(2);
expect(pongFn.mock.calls[0][0]).toBeFalsy();
expect(pongFn.mock.calls[0][1]).toBeUndefined();
expect(pongFn.mock.calls[0][1]).toEqual({ some: 'data' });
expect(pongFn.mock.calls[1][0]).toBeFalsy();
expect(pongFn.mock.calls[1][1]).toBeUndefined();
expect(pongFn.mock.calls[1][1]).toEqual({ some: 'data' });
});
});

0 comments on commit ee6193a

Please sign in to comment.