Writing tests for WebSocket endpoints
In Chapter 8, Defining WebSockets for Two-Way Interactive Communication in FastAPI, we explained how WebSockets work and how you can implement such endpoints in FastAPI. As you may have guessed, writing unit tests for WebSockets endpoints is quite different from what we've seen so far.
Unfortunately, we won't be able to reuse HTTPX since, at the time of writing, this client can't communicate with WebSockets. For the time being, our best bet is to use the default TestClient
provided by Starlette.
To show you this, we'll consider the following WebSocket example:
chapter9_websocket.py
from fastapi import FastAPI, WebSocket from starlette.websockets import WebSocketDisconnect app = FastAPI() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() try: while True: ...