Puppeteer - Mock WebSocket

Viewed 395

Is it possible to mock WebSocket communication in Puppeteer? I'm testing my web app without real backend and mocking Ajax calls with on request handler. But I have to test behavior in response to WebSocket event from server. I have no idea how to achieve this.

1 Answers

I'm using the following to mock WebSocket in puppeteer. This keeps the old one and provides a stub of sorts to allow tests to trigger the WebSocket listener (assigned to onmessage). There might be a more verbose stub but I haven't needed that yet.

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 () {
        // Track old 'WebSocket'
        window.__WebSocket = window.WebSocket;
        window.WebSocket = function () {
          return {
            // Listener - triggered by tests.
            onmessage: function () {},
            // Send event to "backend" - not really used by tests.
            send: function () {
              console.log(arguments);
            }
          };
        };
      });
    `,
  });
});
Related