diff --git a/test/utils/listenersManager.ts b/test/utils/listenersManager.ts new file mode 100644 index 00000000000..f5572349c0d --- /dev/null +++ b/test/utils/listenersManager.ts @@ -0,0 +1,41 @@ +import { expect } from "vitest"; + +/** + * Whether or not it is currently the first time running this manager. + */ +let firstTime = true; + +/** + * The list of listeners that were present during the first time this manager is run. + * These initial listeners are needed throughout the entire test suite, so we never remove them. + */ +const initialListeners: unknown[] = []; + +/** + * The current listener that is only needed for the current test file. + * We plan to delete it during the next test file, when it is no longer needed. + */ +let currentListener; + +export function manageListeners() { + if (firstTime) { + initialListeners.push(...process.listeners("message")); + } else { + expect(process.listeners("message").length).toBeLessThan(7); + + // Remove the listener that was used during the previous test file + if (currentListener) { + process.removeListener("message", currentListener); + currentListener = null; + } + + // Find the new listener that is being used for the current test file + process.listeners("message").forEach((fn) => { + if (!initialListeners.includes(fn)) { + currentListener = fn; + } + }); + } + + firstTime = false; +} diff --git a/test/utils/testFileInitialization.ts b/test/utils/testFileInitialization.ts index dfbec98120a..0f87e18459c 100644 --- a/test/utils/testFileInitialization.ts +++ b/test/utils/testFileInitialization.ts @@ -21,6 +21,7 @@ import MockImage from "#test/utils/mocks/mocksContainer/mockImage"; import Phaser from "phaser"; import InputText from "phaser3-rex-plugins/plugins/inputtext"; import { vi } from "vitest"; +import { manageListeners } from "./listenersManager"; /** * An initialization function that is run at the beginning of every test file (via `beforeAll()`). @@ -95,4 +96,6 @@ export function initTestFile() { initLoggedInUser(); initMysteryEncounters(); } + + manageListeners(); }