thoov/mock-socket

Delay execution of dispatched events

Opened this issue ยท 5 comments

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch mock-socket@9.1.3 for the project I'm working on.

Events from server to client needs to have some delay to mimic network delay.

Here is the diff that solved my problem:

diff --git a/node_modules/mock-socket/dist/mock-socket.js b/node_modules/mock-socket/dist/mock-socket.js
index 2478234..414d406 100644
--- a/node_modules/mock-socket/dist/mock-socket.js
+++ b/node_modules/mock-socket/dist/mock-socket.js
@@ -793,13 +793,16 @@ EventTarget.prototype.dispatchEvent = function dispatchEvent (event) {
     return false;
   }
 
-  listeners.forEach(function (listener) {
-    if (customArguments.length > 0) {
-      listener.apply(this$1, customArguments);
-    } else {
-      listener.call(this$1, event);
-    }
-  });
+  delay(function()
+  {
+    listeners.forEach(function (listener) {
+      if (customArguments.length > 0) {
+        listener.apply(this$1, customArguments);
+      } else {
+        listener.call(this$1, event);
+      }
+    });
+  })
 
   return true;
 };

This issue body was partially generated by patch-package.

Atrue commented

@piranna The dispatchEvent function is already called with the delay helper in the websocket. The server event can be called with delay manually in your code.
Can you please give more details of your problem, what the exact place you need the delay?

Just the part of the server event. I don't want to provide a manual delay on my code, I want the listeners to be executed at least in the next event loop when they are dispatched, not in the same one. This allows me to register some events in the WebSocket, as I would do normally in real code.

Atrue commented

Make sense, you can create a PR, but add the delay in the server's methods where it's needed, not in the dispatchEvent;
It would be very helpful if you also provide a test or example that demonstrates the problem

I think the server method is send(). Why dispatchEvent() is not the correct place? All the server-to-client events are going throught there, so it makes sense to me to add the "network transmission delay" there...

Atrue commented

All the events inside the library are going through dispatchEvent. If the event or the code should be delayed it's wrapped using the delay helper. See websocket.js for examples