vitest-websocket-mock 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,42 @@
1
+ Copyright 2023 Akiomi Kamakura
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
20
+
21
+ The major part of vitest-websocket-mock implementation is based on jest-webosocket-mock, which is subject to the same license.
22
+ Here is the original copyright notice for jest-webosocket-mock:
23
+
24
+ Copyright 2018 Romain Bertrand
25
+
26
+ Permission is hereby granted, free of charge, to any person obtaining a copy
27
+ of this software and associated documentation files (the "Software"), to deal
28
+ in the Software without restriction, including without limitation the rights
29
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30
+ copies of the Software, and to permit persons to whom the Software is
31
+ furnished to do so, subject to the following conditions:
32
+
33
+ The above copyright notice and this permission notice shall be included in all
34
+ copies or substantial portions of the Software.
35
+
36
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
42
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,350 @@
1
+ # Vitest websocket mock
2
+
3
+ [![npm version](https://badge.fury.io/js/vitest-websocket-mock.svg)](https://badge.fury.io/js/vitest-websocket-mock)
4
+ [![Build Status](https://github.com/akiomik/vitest-websocket-mock/actions/workflows/ci.yml/badge.svg)](https://github.com/akiomik/vitest-websocket-mock/actions)
5
+ [![codecov](https://codecov.io/gh/akiomik/vitest-websocket-mock/branch/main/graph/badge.svg?token=40OVYIT90L)](https://codecov.io/gh/akiomik/vitest-websocket-mock)
6
+
7
+ A set of utilities and Vitest matchers to help testing complex websocket interactions.
8
+ A patched fork of [romgain/jest-websocket-mock](https://github.com/romgain/jest-websocket-mock).
9
+
10
+ **Examples:**
11
+ ~~Several examples are provided in the [examples folder](https://github.com/akiomik/vitest-websocket-mock/blob/main/examples/).
12
+ In particular:~~
13
+
14
+ NOTE: These examples are currently not working :cry:
15
+
16
+ - [testing a redux saga that manages a websocket connection](https://github.com/akiomik/vitest-websocket-mock/blob/main/examples/redux-saga/src/__tests__/saga.test.js)
17
+ - [testing a component using the saga above](https://github.com/akiomik/vitest-websocket-mock/blob/main/examples/redux-saga/src/__tests__/App.test.js)
18
+ - [testing a component that manages a websocket connection using react hooks](https://github.com/akiomik/vitest-websocket-mock/blob/main/examples/hooks/src/App.test.tsx)
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ npm install -D vitest-websocket-mock
24
+ ```
25
+
26
+ ## Mock a websocket server
27
+
28
+ ### The `WS` constructor
29
+
30
+ `vitest-websocket-mock` exposes a `WS` class that can instantiate mock websocket
31
+ servers that keep track of the messages they receive, and in turn
32
+ can send messages to connected clients.
33
+
34
+ ```js
35
+ import WS from 'vitest-websocket-mock';
36
+
37
+ // create a WS instance, listening on port 1234 on localhost
38
+ const server = new WS('ws://localhost:1234');
39
+
40
+ // real clients can connect
41
+ const client = new WebSocket('ws://localhost:1234');
42
+ await server.connected; // wait for the server to have established the connection
43
+
44
+ // the mock websocket server will record all the messages it receives
45
+ client.send('hello');
46
+
47
+ // the mock websocket server can also send messages to all connected clients
48
+ server.send('hello everyone');
49
+
50
+ // ...simulate an error and close the connection
51
+ server.error();
52
+
53
+ // ...or gracefully close the connection
54
+ server.close();
55
+
56
+ // The WS class also has a static "clean" method to gracefully close all open connections,
57
+ // particularly useful to reset the environment between test runs.
58
+ WS.clean();
59
+ ```
60
+
61
+ The `WS` constructor also accepts an optional options object as second argument:
62
+
63
+ - `jsonProtocol: true` can be used to automatically serialize and deserialize JSON messages:
64
+
65
+ ```js
66
+ const server = new WS('ws://localhost:1234', { jsonProtocol: true });
67
+ server.send({ type: 'GREETING', payload: 'hello' });
68
+ ```
69
+
70
+ - The `mock-server` options `verifyClient` and `selectProtocol` are directly passed-through to the mock-server's constructor.
71
+
72
+ ### Attributes of a `WS` instance
73
+
74
+ A `WS` instance has the following attributes:
75
+
76
+ - `connected`: a Promise that resolves every time the `WS` instance receives a
77
+ new connection. The resolved value is the `WebSocket` instance that initiated
78
+ the connection.
79
+ - `closed`: a Promise that resolves every time a connection to a `WS` instance
80
+ is closed.
81
+ - `nextMessage`: a Promise that resolves every time a `WS` instance receives a
82
+ new message. The resolved value is the received message (deserialized as a
83
+ JavaScript Object if the `WS` was instantiated with the `{ jsonProtocol: true }`
84
+ option).
85
+
86
+ ### Methods on a `WS` instance
87
+
88
+ - `send`: send a message to all connected clients. (The message will be
89
+ serialized from a JavaScript Object to a JSON string if the `WS` was
90
+ instantiated with the `{ jsonProtocol: true }` option).
91
+ - `close`: gracefully closes all opened connections.
92
+ - `error`: sends an error message to all connected clients and closes all
93
+ opened connections.
94
+ - `on`: attach event listeners to handle new `connection`, `message` and `close` events. The callback receives the `socket` as its only argument.
95
+
96
+ ## Run assertions on received messages
97
+
98
+ `vitest-websocket-mock` registers custom vitest matchers to make assertions
99
+ on received messages easier:
100
+
101
+ - `.toReceiveMessage`: async matcher that waits for the next message received
102
+ by the the mock websocket server, and asserts its content. It will time out
103
+ with a helpful message after 1000ms.
104
+ - `.toHaveReceivedMessages`: synchronous matcher that checks that all the
105
+ expected messages have been received by the mock websocket server.
106
+
107
+ ### Run assertions on messages as they are received by the mock server
108
+
109
+ ```js
110
+ test('the server keeps track of received messages, and yields them as they come in', async () => {
111
+ const server = new WS('ws://localhost:1234');
112
+ const client = new WebSocket('ws://localhost:1234');
113
+
114
+ await server.connected;
115
+ client.send('hello');
116
+ await expect(server).toReceiveMessage('hello');
117
+ expect(server).toHaveReceivedMessages(['hello']);
118
+ });
119
+ ```
120
+
121
+ ### Send messages to the connected clients
122
+
123
+ ```js
124
+ test('the mock server sends messages to connected clients', async () => {
125
+ const server = new WS('ws://localhost:1234');
126
+ const client1 = new WebSocket('ws://localhost:1234');
127
+ await server.connected;
128
+ const client2 = new WebSocket('ws://localhost:1234');
129
+ await server.connected;
130
+
131
+ const messages = { client1: [], client2: [] };
132
+ client1.onmessage = (e) => {
133
+ messages.client1.push(e.data);
134
+ };
135
+ client2.onmessage = (e) => {
136
+ messages.client2.push(e.data);
137
+ };
138
+
139
+ server.send('hello everyone');
140
+ expect(messages).toEqual({
141
+ client1: ['hello everyone'],
142
+ client2: ['hello everyone'],
143
+ });
144
+ });
145
+ ```
146
+
147
+ ### JSON protocols support
148
+
149
+ `vitest-websocket-mock` can also automatically serialize and deserialize
150
+ JSON messages:
151
+
152
+ ```js
153
+ test('the mock server seamlessly handles JSON protocols', async () => {
154
+ const server = new WS('ws://localhost:1234', { jsonProtocol: true });
155
+ const client = new WebSocket('ws://localhost:1234');
156
+
157
+ await server.connected;
158
+ client.send(`{ "type": "GREETING", "payload": "hello" }`);
159
+ await expect(server).toReceiveMessage({ type: 'GREETING', payload: 'hello' });
160
+ expect(server).toHaveReceivedMessages([{ type: 'GREETING', payload: 'hello' }]);
161
+
162
+ let message = null;
163
+ client.onmessage = (e) => {
164
+ message = e.data;
165
+ };
166
+
167
+ server.send({ type: 'CHITCHAT', payload: 'Nice weather today' });
168
+ expect(message).toEqual(`{"type":"CHITCHAT","payload":"Nice weather today"}`);
169
+ });
170
+ ```
171
+
172
+ ### verifyClient server option
173
+
174
+ A `verifyClient` function can be given in the options for the `vitest-websocket-mock` constructor.
175
+ This can be used to test behaviour for a client that connects to a WebSocket server it's blacklisted from for example.
176
+
177
+ **Note** : _Currently `mock-socket`'s implementation does not send any parameters to this function (unlike the real `ws` implementation)._
178
+
179
+ ```js
180
+ test('rejects connections that fail the verifyClient option', async () => {
181
+ new WS('ws://localhost:1234', { verifyClient: () => false });
182
+ const errorCallback = vitest.fn();
183
+
184
+ await expect(
185
+ new Promise((resolve, reject) => {
186
+ errorCallback.mockImplementation(reject);
187
+ const client = new WebSocket('ws://localhost:1234');
188
+ client.onerror = errorCallback;
189
+ client.onopen = resolve;
190
+ })
191
+ // WebSocket onerror event gets called with an event of type error and not an error
192
+ ).rejects.toEqual(expect.objectContaining({ type: 'error' }));
193
+ });
194
+ ```
195
+
196
+ ### selectProtocol server option
197
+
198
+ A `selectProtocol` function can be given in the options for the `vitest-websocket-mock` constructor.
199
+ This can be used to test behaviour for a client that connects to a WebSocket server using the wrong protocol.
200
+
201
+ ```js
202
+ test('rejects connections that fail the selectProtocol option', async () => {
203
+ const selectProtocol = () => null;
204
+ new WS('ws://localhost:1234', { selectProtocol });
205
+ const errorCallback = vitest.fn();
206
+
207
+ await expect(
208
+ new Promise((resolve, reject) => {
209
+ errorCallback.mockImplementationOnce(reject);
210
+ const client = new WebSocket('ws://localhost:1234', 'foo');
211
+ client.onerror = errorCallback;
212
+ client.onopen = resolve;
213
+ })
214
+ ).rejects.toEqual(
215
+ // WebSocket onerror event gets called with an event of type error and not an error
216
+ expect.objectContaining({
217
+ type: 'error',
218
+ currentTarget: expect.objectContaining({ protocol: 'foo' }),
219
+ })
220
+ );
221
+ });
222
+ ```
223
+
224
+ ### Sending errors
225
+
226
+ ```js
227
+ test('the mock server sends errors to connected clients', async () => {
228
+ const server = new WS('ws://localhost:1234');
229
+ const client = new WebSocket('ws://localhost:1234');
230
+ await server.connected;
231
+
232
+ let disconnected = false;
233
+ let error = null;
234
+ client.onclose = () => {
235
+ disconnected = true;
236
+ };
237
+ client.onerror = (e) => {
238
+ error = e;
239
+ };
240
+
241
+ server.send('hello everyone');
242
+ server.error();
243
+ expect(disconnected).toBe(true);
244
+ expect(error.origin).toBe('ws://localhost:1234/');
245
+ expect(error.type).toBe('error');
246
+ });
247
+ ```
248
+
249
+ ### Add custom event listeners
250
+
251
+ #### For instance, to refuse connections:
252
+
253
+ ```js
254
+ it('the server can refuse connections', async () => {
255
+ const server = new WS('ws://localhost:1234');
256
+ server.on('connection', (socket) => {
257
+ socket.close({ wasClean: false, code: 1003, reason: 'NOPE' });
258
+ });
259
+
260
+ const client = new WebSocket('ws://localhost:1234');
261
+ client.onclose = (event: CloseEvent) => {
262
+ expect(event.code).toBe(1003);
263
+ expect(event.wasClean).toBe(false);
264
+ expect(event.reason).toBe('NOPE');
265
+ };
266
+
267
+ expect(client.readyState).toBe(WebSocket.CONNECTING);
268
+
269
+ await server.connected;
270
+ expect(client.readyState).toBe(WebSocket.CLOSING);
271
+
272
+ await server.closed;
273
+ expect(client.readyState).toBe(WebSocket.CLOSED);
274
+ });
275
+ ```
276
+
277
+ ### Environment set up and tear down between tests
278
+
279
+ You can set up a mock server and a client, and reset them between tests:
280
+
281
+ ```js
282
+ beforeEach(async () => {
283
+ server = new WS('ws://localhost:1234');
284
+ client = new WebSocket('ws://localhost:1234');
285
+ await server.connected;
286
+ });
287
+
288
+ afterEach(() => {
289
+ WS.clean();
290
+ });
291
+ ```
292
+
293
+ ## Known issues
294
+
295
+ `mock-socket` has a strong usage of delays (`setTimeout` to be more specific). This means using `vitest.useFakeTimers();` will cause issues such as the client appearing to never connect to the server.
296
+
297
+ While running the websocket server from tests within the vitest-dom environment (as opposed to node)
298
+ you may see errors of the nature:
299
+
300
+ ```bash
301
+ ReferenceError: setImmediate is not defined
302
+ ```
303
+
304
+ You can work around this by installing the setImmediate shim from
305
+ [https://github.com/YuzuJS/setImmediate](https://github.com/YuzuJS/setImmediate) and
306
+ adding `require('setimmediate');` to your `setupTests.js`.
307
+
308
+ ## Testing React applications
309
+
310
+ When testing React applications, `vitest-websocket-mock` will look for
311
+ `@testing-library/react`'s implementation of [`act`](https://reactjs.org/docs/test-utils.html#act).
312
+ If it is available, it will wrap all the necessary calls in `act`, so you don't have to.
313
+
314
+ If `@testing-library/react` is not available, we will assume that you're not testing a React application,
315
+ and you might need to call `act` manually.
316
+
317
+ ## Using `vitest-websocket-mock` to interact with a non-global WebSocket object
318
+
319
+ `vitest-websocket-mock` uses [Mock Socket](https://github.com/thoov/mock-socket)
320
+ under the hood to mock out WebSocket clients.
321
+ Out of the box, Mock Socket will only mock out the global `WebSocket` object.
322
+ If you are using a third-party WebSocket client library (eg. a Node.js
323
+ implementation, like [`ws`](https://github.com/websockets/ws)), you'll need
324
+ to set up a [manual mock](https://jestjs.io/docs/en/manual-mocks#mocking-node-modules):
325
+
326
+ - Create a `__mocks__` folder in your project root
327
+ - Add a new file in the `__mocks__` folder named after the library you want to
328
+ mock out. For instance, for the `ws` library: `__mocks__/ws.js`.
329
+ - Export Mock Socket's implementation in-lieu of the normal export from the
330
+ library you want to mock out. For instance, for the `ws` library:
331
+
332
+ ```js
333
+ // __mocks__/ws.js
334
+
335
+ export { WebSocket as default } from 'mock-socket';
336
+ ```
337
+
338
+ **NOTE** The `ws` library is not 100% compatible with the browser API, and
339
+ the `mock-socket` library that `vitest-websocket-mock` uses under the hood only
340
+ implements the browser API.
341
+ As a result, `vitest-websocket-mock` will only work with the `ws` library if you
342
+ restrict yourself to the browser APIs!
343
+
344
+ ## Examples
345
+
346
+ ~~For a real life example, see the
347
+ [examples directory](https://github.com/akiomik/vitest-websocket-mock/tree/main/examples),
348
+ and in particular the saga tests.~~
349
+
350
+ NOTE: These examples are currently not working :cry:
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @copyright Romain Bertrand 2018
3
+ * @copyright Akiomi Kamakura 2023
4
+ *
5
+ * A simple compatibility method for react's "act".
6
+ * If @testing-library/react is already installed, we just use
7
+ * their implementation - it's complete and has useful warnings.
8
+ * If @testing-library/react is *not* installed, then we just assume
9
+ * that the user is not testing a react application, and use a noop instead.
10
+ */
11
+ type Callback = () => Promise<void | undefined> | void | undefined;
12
+ type AsyncAct = (callback: Callback) => Promise<undefined>;
13
+ type SyncAct = (callback: Callback) => void;
14
+ declare let act: AsyncAct | SyncAct;
15
+ export default act;
16
+ //# sourceMappingURL=act-compat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"act-compat.d.ts","sourceRoot":"","sources":["../src/act-compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,KAAK,QAAQ,GAAG,MAAM,OAAO,CAAC,IAAI,GAAG,SAAS,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC;AACnE,KAAK,QAAQ,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,OAAO,CAAC,SAAS,CAAC,CAAC;AAC3D,KAAK,OAAO,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5C,QAAA,IAAI,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC;AAW5B,eAAe,GAAG,CAAC"}