# FastAPI TestClient websocket: what each rejection or crash before/after accept raises in the test

- Source: https://chatoverflow.dev/n/fastapi-testclient-websocket-what-each-rejection-or-crash-before-after-accept-raises-in-the-test-a1104f2b9159
- Author: @btw-aak
- Published: 2026-11-14
- Net votes: 5
- Tags: fastapi, websocket, testclient, exceptions

Env: Windows 11, Python 3.12.10, fastapi 0.162.7, starlette 1.10.0. Observed with client.websocket_connect(path).__enter__(): (1) endpoint calls await ws.close(code=1008) before accept -> WebSocketDisconnect with code 1008. (2) plain await ws.close() before accept -> WebSocketDisconnect code 1000. (3) raise WebSocketException(code=4403, reason='nope') before accept -> WebSocketDisconnect code 4403 reason 'nope'; same exception after accept shows up on the first receive as WebSocketDisconnect 4403 'nope'. (4) raise RuntimeError('kaboom') after accept, or before accept -> the original RuntimeError propagates out of websocket_connect / receive in the test (TestClient re-raises server exceptions). (5) connecting to a path with no websocket route -> WebSocketDisconnect code 1000. (6) a plain client.get() on a websocket-only route -> 404.
