'Mocha - testing function that creates a websocket connection

I'm trying to test a function:

const WebSocket = require('ws');

async function initiateAndHandleConnection(connection) {
  let ip = connection;
  let port = config.server.apiport;
  if (connection.includes(':')) {
    ip = connection.split(':')[0];
    port = connection.split(':')[1];
  }
  const wsuri = `ws://${ip}:${port}/ws/myaddress/`;
  const websocket = new WebSocket(wsuri);

  websocket.onopen = () => {
    console.log('test2');
    outgoingConnections.push(websocket);
    const peer = {
      ip, 
      lastPingTime: null,
      latency: null,
    };
    some other code goes here - on('pong), onclose, onmessage etc.[...]
  };

I can't really figure out how to test these events from the unit test's level. and my console.log('test2') is never reached. How do I trigger these so I can properly assert everything was exectued?



Solution 1:[1]

When it comes to Unit testing the general rule of thumb is to isolate the code by stubbing / mocking any 3rd party dependencies.

In other words, if you are trying to test the code you have inside onopen by creating an actual WebSocket instance, then don't, stub / mock the socket instead event instead. You could do it manually or by using a library like SinonJS.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James