Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test web sockets - JavaScript

I would like to test web sockets that have been implemented using sockjs.

   var sock = new SockJS('http://mydomain.com/my_prefix');
   sock.onopen = function() {
       console.log('open');
   };
   sock.onmessage = function(e) {
       console.log('message', e.data);
   };
   sock.onclose = function() {
       console.log('close');
   };

I goggled and only found this article. This is not good enough because it's making actual connection rather than faking it.

I also tried SO but only found an unanswered question here.

Someone suggested sinonjs but I'm not able to find any decent example.

I'll appreciate if someone can shed some light on this topic.

like image 681
JS- Avatar asked Oct 09 '13 10:10

JS-


People also ask

How do you write a unit test WebSocket?

the code is as following: Socket = { connect: function () { socket = new WebSocket('ws://localhost:12345'); socket. onopen = function() { console. log('connected to the server'); }; socket.

How do I know if WebSocket is working?

You can check if a WebSocket is connected by doing either of the following: Specifying a function to the WebSocket. onopen event handler property, or; Using addEventListener to listen to the open event.

How do I test a Socket.IO API?

A new Socket.IO request cannot be created by opening a new tab hence we need to go to New > WebSocket Request. Select Socket.IO from the dropdown and key in the HTTP server url in the address bar. We can start sending and receiving message once the connection is established.


1 Answers

When you want to unit-test a feature which accesses an external resource, like in your case a websocket server, the usual approach is to use a mock-object to represent the external resource. A mock-object is an object which looks and behaves like the external resource, but doesn't actually access it. Additionally, it can have logging functionality which allows it to report to the test-code if the tested code behaved like expected.

In your case you would create a mock-SockJS object which has all the relevant properties and methods of a normal SockJS object, but its implementation doesn't actually contact a server. It only logs the method calls and returns the expected response an existing server would send.

Then you would refactor the code you want to test so that it doesn't create the socket itself but instead gets a socket object assigned from the outside (this is called "dependency injection" and is a crucial idiom for writing unit-testable code).

In your real code, you assign a real SockJS object. But in your unit-test, you assign your mock-object. After you called your test-methods you can examine the mock-object to check if the unit sent the expected data to the server.

like image 155
Philipp Avatar answered Sep 20 '22 13:09

Philipp