ws
拦截 WebSocket 连接。
ws
命名空间可帮助你创建事件处理程序来拦截 WebSocket 连接。
¥The ws
namespace helps you create event handlers to intercept WebSocket connections.
调用签名
¥Call signature
ws
命名空间公开了一个名为 link()
的方法。link()
方法创建一个预配置的 WebSocket 链接,以处理与指定 URL 匹配的 WebSocket 连接。
¥The ws
namespace exposes a method called link()
. The link()
method creates a WebSocket link preconfigured to handle WebSocket connections matching the specified URL.
ws.link(url: string | URL | RegExp)
ws.ts
Source code for the `ws` namespace.
事件处理程序
¥Event handler
从 ws.link()
调用返回的对象称为 WebSocket 链接。链接具有以下属性和方法:
¥The object returned from the ws.link()
call is referred to as a WebSocket link. The link has the following properties and methods:
.addEventListener(event, listener)
为传出的 WebSocket 客户端连接添加 连接监听器。
¥Adds a connection listener for the outgoing WebSocket client connections.
.clients
Set<WebSocketClientConnection>
所有活动的 WebSocket 客户端的集合。
¥The set of all active WebSocket clients.
.broadcast(data)
data: string | Blob | ArrayBuffer
将给定的数据发送到所有活动 WebSocket 客户端。
¥Sends the given data to all active WebSocket clients.
const api = ws.link('wss://*')
api.broadcast('hello, everyone')
.broadcastExcept(clients, data)
-
clients: WebSocketClientConnection | Array<WebSocketClientConnection>
-
data: string | Blob | ArrayBuffer
将给定的数据发送到除给定 clients
之外的所有活动 WebSocket 客户端。
¥Sends the given data to all active WebSocket clients except the given clients
.
const api = ws.link('wss://*')
api.addEventListener('connection', ({ client }) => {
api.broadcastExcept(client, 'all except this')
})
你还可以提供 WebSocket 客户端连接数组作为 clients
的参数:
¥You can also provide an array of WebSocket client connections as the argument to clients
:
const ignoredClients = Array.from(api.clients).filter((client) => {
return client.url.includes('abc')
})
api.broadcastExcept(ignoredClients, 'hello')
连接监听器
¥Connection listener
参数 | 类型 | 描述 |
---|---|---|
client | WebSocketClientConnection | 传出 WebSocket 客户端连接对象。 |
server | WebSocketServerConnection | 实际的 WebSocket 服务器连接对象。 |
params | Record<string, string> | 从连接 url 中提取的路径参数。 |
info | WebSocketConnectionInfo | 有关此 WebSocket 连接的额外信息。 |
连接监听器在每个传出的 WebSocket 客户端连接上调用。
¥The connection listener is called on every outgoing WebSocket client connection.
import { ws } from 'msw'
import { setupWorker } from 'msw/browser'
const api = ws.link('wss://chat.example.com')
const worker = setupWorker(
api.addEventListener('connection', () => {
console.log('client connected!')
}),
)
await worker.start()
const socket = new WebSocket('wss://chat.example.com')
socket.onopen = () => {
console.log('connection established!')
}
在此示例中,与 wss://chat.example.com
的 WebSocket 连接在 api
事件处理程序上发出 "connection"
事件,因为端点与提供给 ws.link()
调用的端点匹配。由于连接成功,"open"
事件也会在 socket
实例上分派。
¥In this example, the WebSocket connection to wss://chat.example.com
emits the "connection"
event on the api
event handler because the endpoint matches the one provided to the ws.link()
call. Since the connection is successful, the "open"
event is also dispatched on the socket
instance.
WebSocketClientConnection
从服务器的角度来看,WebSocketClientConnection
对象表示被拦截的 WebSocket 客户端连接。这意味着客户端上的 message
事件代表由客户端发送并由 “server” 接收的消息。
¥The WebSocketClientConnection
object represents an intercepted WebSocket client connection from the server’s perspective. This means that the message
event on the client stands for a message sent by the client and received by the “server”.
.addEventListener(event, listener, options)
向给定的客户端事件添加监听器。这些是受支持的客户端事件:
¥Adds a listener to the given client event. These are the supported client events:
事件名称 | 描述 |
---|---|
message | 当此客户端发送消息时分派。 |
error | 当此客户端连接因错误而关闭时分派。 |
close | 当此客户端关闭时(例如由你的应用关闭)分派。 |
.removeEventListener(event, listener, options)
删除给定客户端事件的监听器。
¥Removes the listener for the given client event.
.send(data)
data: string | Blob | ArrayBuffer
将数据发送到 WebSocket 客户端。这相当于客户端从服务器接收该数据。
¥Sends data to the WebSocket client. This is equivalent to the client receiving that data from the server.
api.addEventListener('connection', ({ client }) => {
client.send('hello')
client.send(new Blob(['hello']))
client.send(new TextEncoder().encode('hello'))
})
.close(code, reason)
-
code: number | undefined
,默认:1000
¥
code: number | undefined
, default:1000
-
reason: string | undefined
关闭活动的 WebSocket 客户端连接。
¥Closes the active WebSocket client connection.
api.addEventListener('connection', ({ client }) => {
client.close()
})
与 WebSocket.prototype.close()
方法不同,client.close()
方法接受不可配置的关闭代码。这允许你根据服务器端错误模拟客户端关闭场景。
¥Unlike the WebSocket.prototype.close()
method, the client.close()
method accepts non-configurable close codes. This allows you to emulate client close scenarios based on server-side errors.
api.addEventListener('connection', ({ client }) => {
client.addEventListener('message', (event) => {
client.close(1003, 'Invalid data')
})
})
你还可以实现自定义关闭代码和原因:
¥You can also implement custom close code and reason:
api.addEventListener('connection', ({ client }) => {
client.close(4000, 'Custom close reason')
})
WebSocketServerConnection
WebSocketServerConnection
对象代表实际的 WebSocket 服务器连接。
¥The WebSocketServerConnection
object represents the actual WebSocket server connection.
.connect()
与实际 WebSocket 服务器建立连接。
¥Establishes connection to the actual WebSocket server.
api.addEventListener('connection', ({ server }) => {
server.connect()
})
.addEventListener(event, listener, options)
向原始服务器 WebSocket 连接添加监听器。支持的事件有:
¥Adds a listener to the original server WebSocket connection. The supported events are:
事件名称 | 描述 |
---|---|
open | 当与原始服务器的连接已打开时分派。 |
message | 当原始服务器发送消息时分派。 |
error | 当原始服务器连接因错误而关闭时分派。 |
close | 当原始服务器连接已关闭时分派。 |
.removeEventListener(event, listener, options)
删除给定服务器事件的监听器。
¥Removes the listener for the given server event.
.send(data)
data: string | Blob | ArrayBuffer
将数据发送到实际的 WebSocket 服务器。这相当于客户端将该数据发送到服务器。
¥Sends data to the actual WebSocket server. This is equivalent to the client sending this data to the server.
api.addEventListener('connection', ({ server }) => {
server.connect()
server.addEventListener('message', (event) => {
if (event.data === 'hello from server') {
server.send('hello from client')
}
})
})
.close(code, reason)
关闭底层的原始 WebSocket 服务器连接。提供自定义关闭 code
和 reason
。
¥Closes the underlying original WebSocket server connection. Provides a custom close code
and reason
.
api.addEventListener('connection', ({ server }) => {
server.connect()
server.close()
})
WebSocketConnectionInfo
connection
事件监听器上的 info
参数包含额外的 WebSocket 连接信息。
¥The info
argument on the connection
event listener contains additional WebSocket connection infromation.
属性名称 | 类型 | 描述 |
---|---|---|
protocols | string | string[] | undefined | 建立此 WebSocket 连接时使用的协议列表。 |
api.addEventListener('connection', ({ info }) => {
if (info.protocols?.includes('chat')) {
// ...
}
})