Skip to main content
FastAPI Docs
current

Search documentation

Type to search this documentation.

Testing WebSockets

You can use the same TestClient to test WebSockets.

For this, you use the TestClient in a with statement, connecting to the WebSocket:

Python 3.10+
from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom fastapi.websockets import WebSocketapp = FastAPI()@app.get("/")async def read_main():    return {"msg": "Hello World"}@app.websocket("/ws")async def websocket(websocket: WebSocket):    await websocket.accept()    await websocket.send_json({"msg": "Hello WebSocket"})    await websocket.close()def test_read_main():    client = TestClient(app)    response = client.get("/")    assert response.status_code == 200    assert response.json() == {"msg": "Hello World"}def test_websocket():    client = TestClient(app)    with client.websocket_connect("/ws") as websocket:        data = websocket.receive_json()        assert data == {"msg": "Hello WebSocket"}
Suggest an edit

Propose a replacement for this page. The site team reviews it before applying any changes.

Export
Documentation menu