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.
For this task, we’ll need to tweak our test_client
fixture a little bit. Indeed, HTTPX doesn’t have built-in support to communicate with WebSockets. Hence, we’ll need to use a plugin, HTTPX WS. Let’s install it with the following command:
(venv) $ pip install httpx-ws
To enable support for WebSockets on our test client, we’ll change it like this:
chapter09_websocket_test.py
from httpx_ws.transport import ASGIWebSocketTransport@pytest_asyncio.fixture async def test_client(): async with LifespanManager(app): async with httpx.AsyncClient( ...