tests: Refactor waitForSocketEvent() to improve readability

This commit is contained in:
Richard Hansen 2021-10-30 22:28:12 -04:00
parent 3132235f2c
commit 23a98e5946

View file

@ -87,27 +87,43 @@ exports.waitForSocketEvent = async (socket, event) => {
'reconnect_error', 'reconnect_error',
'reconnect_failed', 'reconnect_failed',
]; ];
const handlers = {}; const handlers = new Map();
let timeoutId; let cancelTimeout;
return new Promise((resolve, reject) => { try {
timeoutId = setTimeout(() => reject(new Error(`timed out waiting for ${event} event`)), 1000); const timeoutP = new Promise((resolve, reject) => {
for (const event of errorEvents) { const timeout = setTimeout(() => {
handlers[event] = (errorString) => { reject(new Error(`timed out waiting for ${event} event`));
cancelTimeout = () => {};
}, 1000);
cancelTimeout = () => {
clearTimeout(timeout);
resolve();
cancelTimeout = () => {};
};
});
const errorEventP = Promise.race(errorEvents.map((event) => new Promise((resolve, reject) => {
handlers.set(event, (errorString) => {
logger.debug(`socket.io ${event} event: ${errorString}`); logger.debug(`socket.io ${event} event: ${errorString}`);
reject(new Error(errorString)); reject(new Error(errorString));
}; });
} })));
// This will overwrite one of the above handlers if the user is waiting for an error event. const eventP = new Promise((resolve) => {
handlers[event] = (...args) => { // This will overwrite one of the above handlers if the user is waiting for an error event.
logger.debug(`socket.io ${event} event`); handlers.set(event, (...args) => {
if (args.length > 1) return resolve(args); logger.debug(`socket.io ${event} event`);
resolve(args[0]); if (args.length > 1) return resolve(args);
}; resolve(args[0]);
Object.entries(handlers).forEach(([event, handler]) => socket.on(event, handler)); });
}).finally(() => { });
clearTimeout(timeoutId); for (const [event, handler] of handlers) socket.on(event, handler);
Object.entries(handlers).forEach(([event, handler]) => socket.off(event, handler)); // timeoutP and errorEventP are guaranteed to never resolve here (they can only reject), so the
}); // Promise returned by Promise.race() is guaranteed to resolve to the eventP value (if
// the event arrives).
return await Promise.race([timeoutP, errorEventP, eventP]);
} finally {
cancelTimeout();
for (const [event, handler] of handlers) socket.off(event, handler);
}
}; };
/** /**