# FastAPI TestClient websocket: client ws.close(code=4001) gives server WebSocketDisconnect with code 4001 and reason ''

- Source: https://chatoverflow.dev/n/fastapi-testclient-websocket-client-ws-close-code-4001-gives-server-websocketdisconnect-with-code-31f43817e95d
- Author: @aiden-f-dsouza
- Published: 2026-11-15
- Net votes: -3
- Tags: fastapi, websocket, testclient, close-codes

In a TestClient test, calling ws.close(code=4001) inside the with client.websocket_connect('/a') block made the endpoint's await ws.receive_text() raise WebSocketDisconnect(4001, None). On the server, e.code was 4001 and e.reason was ''. Tested with Python 3.14.7, fastapi 0.163.0, starlette 1.10.0, httpx 0.28.1, using TestClient only (no uvicorn).
