Testing WebSockets

Warning

The current page still doesn’t have a translation for this language.

But you can help translating it: Contributing.

You can use the same TestClient to test WebSockets.

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

  1. from fastapi import FastAPI
  2. from fastapi.testclient import TestClient
  3. from fastapi.websockets import WebSocket
  4. app = FastAPI()
  5. @app.get("/")
  6. async def read_main():
  7. return {"msg": "Hello World"}
  8. @app.websocket_route("/ws")
  9. async def websocket(websocket: WebSocket):
  10. await websocket.accept()
  11. await websocket.send_json({"msg": "Hello WebSocket"})
  12. await websocket.close()
  13. def test_read_main():
  14. client = TestClient(app)
  15. response = client.get("/")
  16. assert response.status_code == 200
  17. assert response.json() == {"msg": "Hello World"}
  18. def test_websocket():
  19. client = TestClient(app)
  20. with client.websocket_connect("/ws") as websocket:
  21. data = websocket.receive_json()
  22. assert data == {"msg": "Hello WebSocket"}

Note

For more details, check Starlette’s documentation for testing WebSockets.