Testing WebSockets¶
You can use the sameTestClient to test WebSockets.
For this, you use theTestClient in awith statement, connecting to the WebSocket:
fromfastapiimportFastAPIfromfastapi.testclientimportTestClientfromfastapi.websocketsimportWebSocketapp=FastAPI()@app.get("/")asyncdefread_main():return{"msg":"Hello World"}@app.websocket("/ws")asyncdefwebsocket(websocket:WebSocket):awaitwebsocket.accept()awaitwebsocket.send_json({"msg":"Hello WebSocket"})awaitwebsocket.close()deftest_read_main():client=TestClient(app)response=client.get("/")assertresponse.status_code==200assertresponse.json()=={"msg":"Hello World"}deftest_websocket():client=TestClient(app)withclient.websocket_connect("/ws")aswebsocket:data=websocket.receive_json()assertdata=={"msg":"Hello WebSocket"}Note
For more details, check Starlette's documentation fortesting WebSockets.







