9

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.

Community
  • 1
  • 1
JS-
  • 937
  • 1
  • 9
  • 12

1 Answers1

4

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.

Community
  • 1
  • 1
Philipp
  • 60,671
  • 9
  • 107
  • 141
  • 2
    Thanks for feedback, it looks like lots of work. I'm looking for something ready made. Eg, jasmine has got all the tools for creating fake AJAX calls. Web sockets are becoming more and more popular. Is there any library that gives me these mock objects out of box? – JS- Oct 09 '13 at 14:45
  • 3
    @user2855314 Jasmin implements mock objects as decorators around actual objects. Its terminology for this is `Spy`. The `SpyOn` method can be chained with a call to `andCallFake(function)` which delegates the method-call to your own implementation. This prevents the object to actually try to contact a server and instead returns what your implementation returns. – Philipp Oct 09 '13 at 15:26
  • 2
    @Philipp, can you please provide any example for this? – Suman Bogati Apr 10 '14 at 11:20