简体   繁体   English

如何对Web套接字进行单元测试 - JavaScript

[英]How to unit test web sockets - JavaScript

I would like to test web sockets that have been implemented using sockjs . 我想测试使用sockjs实现的Web套接字。

   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 . 我g目结舌,只发现了这篇文章 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. 有人提出了sinonjs,但我找不到任何体面的例子。

I'll appreciate if someone can shed some light on this topic. 如果有人能够对这个话题有所了解,我将不胜感激。

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. 当您想要对访问外部资源的功能进行单元测试时,就像在您的情况下使用websocket服务器一样,通常的方法是使用模拟对象来表示外部资源。 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. 在您的情况下,您将创建一个mock-SockJS对象,该对象具有普通SockJS对象的所有相关属性和方法,但其实现实际上并未与服务器联系。 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. 在您的实际代码中,您分配一个真正的SockJS对象。 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. 调用测试方法后,可以检查模拟对象以检查设备是否将预期数据发送到服务器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM