Skip to content

Commit

Permalink
Refactor : Moved to delay functionality to util
Browse files Browse the repository at this point in the history
  • Loading branch information
joyguptaa committed Mar 16, 2024
1 parent 46c8021 commit f5e4e5d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/utils/guildRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
5 changes: 5 additions & 0 deletions src/utils/sleep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function sleep(delay = 1000) {
return new Promise((resolve) => {
setTimeout(resolve, delay);
});
}
18 changes: 18 additions & 0 deletions tests/unit/utils/sleep.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});

0 comments on commit f5e4e5d

Please sign in to comment.