diff --git a/src/utils/guildRole.ts b/src/utils/guildRole.ts index ef45c912..11eb34cb 100644 --- a/src/utils/guildRole.ts +++ b/src/utils/guildRole.ts @@ -21,6 +21,7 @@ import { } from "../typeDefinitions/discordMessage.types"; import { GuildRole, Role } from "../typeDefinitions/role.types"; import createDiscordHeaders from "./createDiscordHeaders"; +import { sleep } from "./sleep"; export async function createGuildRole( body: createNewRole, @@ -188,9 +189,7 @@ export async function mentionEachUserInMessage({ console.error(`Failed to mention a user`); } }); - await new Promise((resolve) => - setTimeout(resolve, waitTillNextAPICall * 1000) - ); + await sleep(waitTillNextAPICall * 1000); waitTillNextAPICall = 0; } if (failedUsers.length > 0) { diff --git a/src/utils/sleep.ts b/src/utils/sleep.ts new file mode 100644 index 00000000..9e46de17 --- /dev/null +++ b/src/utils/sleep.ts @@ -0,0 +1,5 @@ +export function sleep(delay = 1000) { + return new Promise((resolve) => { + setTimeout(resolve, delay); + }); +} diff --git a/tests/unit/utils/sleep.test.ts b/tests/unit/utils/sleep.test.ts new file mode 100644 index 00000000..70a57005 --- /dev/null +++ b/tests/unit/utils/sleep.test.ts @@ -0,0 +1,18 @@ +import { sleep } from "../../../src/utils/sleep"; +jest.useFakeTimers(); + +describe("sleep function", () => { + afterAll(() => jest.useRealTimers()); + test("should resolve after the specified delay", async () => { + const delay = 2000; + const promise = sleep(delay); + jest.advanceTimersByTime(delay); + await expect(promise).resolves.toBeUndefined(); + }); + + test("should resolve after default delay if no delay is provided", async () => { + const promise = sleep(); + jest.advanceTimersByTime(1000); + await expect(promise).resolves.toBeUndefined(); + }); +});