绑定
为了在模拟第三方 WebSocket 客户端时提供更熟悉的体验,MSW 使用了绑定。绑定是标准 WebSocket
类的封装器,它封装了第三方特定的行为(例如消息解析),并为你提供了类似于绑定的第三方库的公共 API。
¥To provide a more familiar experience when mocking third-party WebSocket clients, MSW uses bindings. A binding is a wrapper over the standard WebSocket
class that encapsulates the third-party-specific behaviors, such as message parsing, and gives you a public API similar to that of the bound third-party library.
例如,以下是使用 MSW 和指定的 SocketIO 绑定处理 Socket.IO 通信的方法:
¥For example, here’s how to handle Socket.IO communication using MSW and a designated SocketIO binding:
import { ws } from 'msw'
import { toSocketIo } from '@mswjs/socket.io-binding'
const chat = ws.link('wss://chat.example.com')
export const handlers = [
chat.addEventListener('connection', (connection) => {
const io = toSocketIo(connection)
io.client.on('hello', (username) => {
io.client.emit('message', `hello, ${username}!`)
})
}),
]
@mswjs/socket.io-binding
Connection wrapper for mocking Socket.IO with MSW.
请注意,绑定并不意味着涵盖相应第三方库的所有公共 API。除非该库提供绑定,否则无法保持完全兼容性。
¥Note that binding is not meant to cover all the public APIs of the respective third-party library. Unless the binding is shipped by that library, maintaining full compatibility is not feasible.