I'm having trouble connecting to a WebSocket as it keeps returning an error. Below is the code I am using for testing:
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);
}
});
And here is my WebSocket class:
import { WebSocket } from 'ws';
export const connectToWebSocket = (url: string, authToken: string): Promise<WebSocket> => {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url);
ws.on('open', () => {
console.log('WebSocket connection established.');
const authMessage = JSON.stringify({ token: authToken });
ws.send(authMessage);
resolve(ws);
});
ws.on('message', (data) => {
console.log('Received message:', data);
});
ws.on('error', (error) => {
console.error('WebSocket error:', error.message);
reject(error);
});
ws.on('close', () => {
console.log('WebSocket connection closed.');
});
});
};
The issue arises when trying to establish the WebSocket connection and I see the following error message: WebSocket connection established. WebSocket connection failed: ReferenceError: WebSocket is not defined