playwright websocket closed before test finished: how to fix
Diagnoses Playwright tests where the websocket closes early. Use when the socket 'close' fires before assertions complete. Not for server-side socket bugs.
TL;DR
The socket usually closes because the page navigated or the test ended before the message arrived. Await the expected message with a promise before finishing the test, and listen for the close event to log why it closed.
The query
playwright websocket closed before test finished: how to fixUse this when
- websocket closes mid-test
- socket messages never arrive
- live-update tests flake
Not for
- the server closing idle sockets
- testing the server's socket logic
- socket auth failures
Steps
- Add a websocket handler that logs 'close' with its code and reason. Expected output: log lines showing when and why the socket closed.
- Check whether the test navigates or closes the page before awaiting the socket message. Expected output: the close logged before the message wait resolves.
- Restructure to await the message first: create the message promise before the triggering click. Expected output: the message promise is created before the trigger.
- Keep the page open until assertions on the message complete; move teardown after them. Expected output: assertions run while the socket is still open.
- Re-run and confirm the message arrives before any close. Expected output: the message log precedes the close log.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_YhWLSETF9z4EkXd4pOe4jw
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.