Mocked WebSocket event listeners. While this is public, you should attach a listener using MockClientWebSocket.addEventListener method and remove them with MockClientWebSocket.removeEventListener, as you would with a normal WebSocket instance.
Implements and mocks the standard WebSocket.readyState
property.
This callback will be called whenever a message is sent to or from the WebSocket. This is set
via the constructor option sendCallback
.
import {MockClientWebSocket, connectWebSocket} from '@rest-vir/define-service';
const webSocket = await connectWebSocket(myService.webSockets['/my-socket'], {
webSocketConstructor: createMockClientWebSocketConstructor(
myService.webSockets['/my-socket'],
{
sendCallback: (message) => {
// handle the sent message here
console.log('handled message:', message);
},
},
),
});
Implements and mocks the standard WebSocket.addEventListener
property but with message type
safety.
Manually close and cleanup the WebSocket.
Dispatch a WebSocket event. This is primarily used within the MockClientWebSocket class itself but may also be used externally to test various WebSocket scenarios.
Note that dispatching 'open'
and 'close'
events will not actually close or open the
WebSocket. Use the MockClientWebSocket.open and MockClientWebSocket.close
methods instead (which appropriately dispatch their events).
Manually set the WebSocket connection as opened. This is only necessary to use if you've set the constructor options to
Implements and mocks the standard WebSocket.removeEventListener
property but with message
type safety.
Implements and mocks the standard WebSocket.send
property but with message type safety.
Sends a message as if it came from the WebSocket host. Use this to unit test client-side WebSockets without needing a running host.
A mock WebSocket constructor for connections from the client side. This can be passed to
connectWebSocket
as thewebSocketConstructor
to allow unit testing on a client without spinning up an entire host to serve the WebSocket connection.Example
Package
@rest-vir/define-service