Puppeteer: Simulating WebSocket Connections

How can I simulate WebSocket communication in Puppeteer? I'm currently testing my web application without a real backend and have been able to mock Ajax calls using the on request handler. However, I now need to test how my application responds to WebSocket events from the server. Can someone provide guidance on how to accomplish this?

Answer №1

In my puppeteer automation, I have implemented the following code snippet to mock the WebSocket functionality. This code preserves the existing WebSocket object while creating a stub that allows tests to simulate the behavior of the WebSocket listener (specifically assigned to onmessage). Although there may be more elaborate ways to create a stub, this simple approach has sufficed for my current needs.

browser.on('targetchanged', async target => {
  const targetPage = await target.page();
  const client = await targetPage.target().createCDPSession();
  await client.send('Runtime.evaluate', {
    expression: `
      window.document.addEventListener("DOMContentLoaded", function () {
        // Preserve old 'WebSocket'
        window.__WebSocket = window.WebSocket;
        window.WebSocket = function () {
          return {
            // Listener - triggered by tests.
            onmessage: function () {},
            // Simulate sending event data to "backend" (not crucial for tests).
            send: function () {
              console.log(arguments);
            }
          };
        };
      });
    `,
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deleting a page reference from the page history stack in Angular 4

I am working on my angular web application and I am looking for a way to remove a specific page reference from the angular page history stack. For example, if I navigate from the login page to the dashboard page, I want to remove the login page reference f ...

Encountering an unexpected token in Javascript when using conditionals

I am currently attempting to integrate a JavaScript condition within a listed order, containing two radio buttons that need to be checked in order to progress to the following list based on the selection. <li data-input-trigger> <label class="fs- ...

Encountering the error "TypeScript: Property 'FOO' does not exist on type" when trying to add a property to an object that has already been declared

Encountering an error in TypeScript: error TS2339: Property 'FOO' is not found in type '{ stuff ... 201 more ...; }'. Constants.FOO.forEach((item) => { ~~~ Arising from this scenario: // Constants.js const Constants = { ...

Prevent other keydown handlers from interfering with Material UI TextField events' propagation

Having an issue in my React app where I am unable to prevent the propagation of keyboard events coming from Material UI TextField. For instance, when pressing the backspace key inside the textfield, it triggers an unwanted delete operation in my authoring ...

What is the best way to configure maxSockets in Node.js while working with Express?

Can the maximum number of sockets in Node.js be adjusted while working with the Express framework? More information can be found here. ...

Comparison: NumberFormatter versus NumberFormat in PHP and JavaScript

My attempts to format currency seem to yield inconsistent results. Using PHP with the NumberFormatter class, here's a snippet of my code: $number = 5125.99; echo getInternationallyFormattedCurrency($number, 'tl-PH', 'PHP'); echo & ...

Why is it that the "await" keyword lacks the ability to truly await?

I created this code to access the google calendar API and retrieve information. To make it easier to understand, I added the variable x to the function. Initially, I expected x to be displayed as 1, however, it consistently shows up as 1. The main issue ...

Integrate CSS and JavaScript files into Node Express

I am facing an issue including my CSS file and JavaScript file in a node-express application, as I keep getting a 404 not found error. Here is the code snippet that I am using: 1. In server.js var http = require('http'); var app = require(' ...

What is the best way to display my to-do list items within a React component

I'm working on a straightforward todo application using fastapi and react. How can I display my todos? I attempted to use {todo.data}, but it's not functioning as expected. Here is my Todos.js component: import React, { useEffect, useState } fro ...

`Error encountered when JSONP script is returning incorrect MIME Type`

I am currently faced with the task of extracting data from a third-party feed that provides a JSON file. Unfortunately, I do not have access to the server to enable CORS, so after conducting some research I learned about using JSONP. When checking the Chro ...

Continuously apply the template in a recursive manner in Angular 2 without reintroducing any duplicated components

Recently, I delved into the world of angular 2 and found it to be quite fascinating. However, I'm currently facing a roadblock and could really use some assistance. The scenario is as follows: I am working on creating a select box with checkboxes in ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Generate a variety of files using GraphicsMagick

I'm trying to enhance my function that deals with uploaded images. Currently, it captures the image, converts it, and saves only one version of it on the server. However, I would like to modify it to achieve the following goals: Goals: Save multipl ...

Create a never-ending jQuery script that is simple and straightforward

My WordPress website features an accordion element that usually functions well by toggling classes when tabs are clicked. However, there is one issue where clicking on a tab does not automatically close other opened tabs. To address this, I added the follo ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...

Utilizing doT.js for Organizing Nested Lists from Arrays and Objects

Can nested lists be generated with doT.js? My current code only processes the first object in the array (g1) and ignores the rest. Is there a solution for this using doT.js? The desired result should be: G1 T11 T12 T13 G2 T21 T22 T23 $(document) ...

The mobile menu is not responding to the click event

Upon clicking the mobile menu hamburger button, I am experiencing a lack of response. I expected the hamburger menu to transition and display the mobile menu, but it seems that neither action is being triggered. Even though I can confirm that my javascrip ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

How can I include line breaks using HTML `<br>` tags in a textarea field that is filled with data from a MySQL

Within a modal, I am showcasing a log inside a read-only <textarea> field that contains data fetched from my MySQL database. Below this, there is a writable <textarea> field where users can input updates to the log, which are then added to the ...

Ending asynchronous tasks running concurrently

Currently, I am attempting to iterate through an array of objects using a foreach loop. For each object, I would like to invoke a function that makes a request to fetch a file and then unzips it with zlib, but this needs to be done one at a time due to the ...