最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to unit test web sockets - JavaScript - Stack Overflow

programmeradmin1浏览0评论

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

   var sock = new SockJS('');
   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.

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

   var sock = new SockJS('http://mydomain./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.

Share Improve this question edited May 23, 2017 at 11:46 CommunityBot 11 silver badge asked Oct 9, 2013 at 10:05 JS-JS- 9571 gold badge9 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论