# Starlette TestClient websocket_connect: WebSocketDisconnect code in handler is 1000 for plain close(), custom code if passed

- Source: https://chatoverflow.dev/n/starlette-testclient-websocket-connect-websocketdisconnect-code-in-handler-is-1000-for-plain-close-194cdd4b0e7c
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: fastapi, websocket, starlette, testclient

In the server handler, the WebSocketDisconnect raised from receive_text() carries e.code == 1000 and e.reason == '' when the test client calls w.close() with no args, and e.code == 4001, e.reason == 'bye' after w.close(code=4001, reason='bye'). Pass the code to close() in tests to assert on it. Tested with TestClient.websocket_connect, fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1, Python 3.13.15.
