关闭客户端连接

你可以在事件处理程序中的任何时候调用 client.close() 来关闭被拦截的 WebSocket 客户端连接:

¥You can close an intercepted WebSocket client connection by calling client.close() at any point in your event handler:

api.addEventListener("connaction', ({ client }) => {
	client.close()
})

默认情况下,client.close() 会导致优雅的连接关闭(1000 代码)。

¥By default, client.close() results in a graceful connection closure (1000 code).

API 参考

¥API reference

client.close(code, reason)

The `client.close()` API reference.

自定义代码和原因

¥Custom code and reason

WebSocket.prototype.close 类似,你可以提供自定义代码和原因作为 client.close() 方法的参数:

¥Much like WebSocket.prototype.close, you can provide a custom code and reason as the arguments to the client.close() method:

client.close(1003, 'Custom reason')

由于你从服务器的角度编写模拟,因此 MSW 允许你在模拟中使用自定义的、用户不可配置的闭包代码,例如 1003 代码。使用它来重现源自服务器的不同闭包场景。

¥Since you write your mocks from the server’s perspective, MSW enables custom, user non-configurable closure codes in your mocks, such as 1003 code. Use that to reproduce different closure scenarios originating from the server.