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);
}
};
};
});
`,
});
});