Skip to content

Commit 5143e91

Browse files
committed
add websocket tests
1 parent fb91e2e commit 5143e91

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

test/test.js

+67
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,73 @@ describe('DataChannel streams', () => {
179179
});
180180
});
181181

182+
describe('Websocket', () => {
183+
const webSocketServer = new nodeDataChannel.WebSocketServer({ bindAddress: '127.0.0.1', port: 1987 });
184+
const clientSocket = new nodeDataChannel.WebSocket();
185+
186+
// Mocks
187+
const clientOnOpenMock = jest.fn();
188+
const clientOnMessageMock = jest.fn();
189+
const clientOnCLosedMock = jest.fn();
190+
191+
const webServerOnClientMock = jest.fn();
192+
const webServerOnOpenMock = jest.fn();
193+
const webServerOnMessageMock = jest.fn();
194+
const webServerOnClosedMock = jest.fn();
195+
196+
webSocketServer.onClient((serverSocket) => {
197+
webServerOnClientMock();
198+
199+
serverSocket.onOpen(() => {
200+
webServerOnOpenMock();
201+
});
202+
203+
serverSocket.onMessage((message) => {
204+
webServerOnMessageMock(message);
205+
serverSocket.sendMessage('reply to ' + message);
206+
serverSocket.close();
207+
});
208+
209+
serverSocket.onClosed(() => {
210+
webServerOnClosedMock();
211+
serverSocket.close();
212+
});
213+
});
214+
215+
test('can create a websocket client and connect to a server', (done) => {
216+
clientSocket.open('ws://127.0.0.1:1987');
217+
clientSocket.onOpen(() => {
218+
clientOnOpenMock();
219+
clientSocket.sendMessage('Hello');
220+
});
221+
222+
clientSocket.onMessage((message) => {
223+
clientOnMessageMock(message);
224+
});
225+
226+
clientSocket.onClosed(() => {
227+
clientOnCLosedMock();
228+
});
229+
230+
setTimeout(() => {
231+
expect(clientOnMessageMock.mock.calls[0][0]).toEqual('reply to Hello');
232+
expect(clientOnOpenMock.mock.calls.length).toBe(1);
233+
expect(clientOnMessageMock.mock.calls.length).toBe(1);
234+
expect(clientOnCLosedMock.mock.calls.length).toBe(1);
235+
236+
expect(webServerOnMessageMock.mock.calls[0][0]).toEqual('Hello');
237+
expect(webServerOnOpenMock.mock.calls.length).toBe(1);
238+
expect(webServerOnMessageMock.mock.calls.length).toBe(1);
239+
expect(webServerOnClosedMock.mock.calls.length).toBe(0);
240+
241+
clientSocket.close();
242+
webSocketServer.stop();
243+
244+
done();
245+
}, 3000);
246+
});
247+
});
248+
182249
afterAll(() => {
183250
// Properly cleanup so Jest does not complain about asynchronous operations that weren't stopped.
184251
nodeDataChannel.cleanup();

0 commit comments

Comments
 (0)