connect to websocket with playwright – Websocket

by
Ali Hasan
playwright react-typescript websocket

The Problem:

I’m trying to connect to a WebSocket using Playwright, but I’m getting an error saying WebSocket connection failed: ReferenceError: WebSocket is not defined. This error indicates that WebSocket constructor is not available. I’ve included code for connecting to the WebSocket and the error I’m encountering. Can you help me understand what’s causing this error and how to resolve it?

The Solutions:

Solution 1: Use the WebSocket object from the ‘ws’ library

In your test file, import the WebSocket object from the ‘ws’ library. Here’s an example:

import { WebSocket } from 'ws';

test(`connection`, async () => {
  const url = endpoint.webSocketURL;
  const authToken = authorizationValue;
  try {
    const websocket = await connectToWebSocket(url, authToken);
    expect(websocket.readyState, "Verify Trade Streaming connection").toBe(WebSocket.OPEN);
    websocket.onmessage = (event) => {
      const data = event.data;
      console.log('Received message: ', data);
    };
  } catch (error) {
    console.error("WebSocket connection failed: ", error);
  }
});

Make sure to install the ‘ws’ library using a package manager like npm or yarn before running your test.

Q&A

What causes the error "WebSocket is not defined"?

Native WebSocket object is not imported in the test file.

How to fix the error "WebSocket is not defined"?

Import the WebSocket object from the ‘ws’ library in the test file.

Video Explanation:

The following video, titled "Playwright Automation - Lesson 02 | Architecture | Advantages ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

... WebSocket protocol, (which is way faster than HTTP) you can send back to back requests without terminating connection ...