Skip to content

Commit

Permalink
feat: Implement cancellable, promisified sleep
Browse files Browse the repository at this point in the history
Unfortunately jest cannot currently handle mocking setTimeout from
"node:timers/promises", see issue
sinonjs/fake-timers#469 .
We do not wish to mix callbacks and async functions. To keep our code
testable with jest, let's create our own cancellable wrapper around the
callback-based setTimeout.
  • Loading branch information
haphut committed Dec 13, 2023
1 parent d461bbb commit 86e1627
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/util/sleep.ts
@@ -0,0 +1,46 @@
/**
* Unfortunately jest cannot currently handle mocking setTimeout from
* "node:timers/promises", see issue
* https://github.com/sinonjs/fake-timers/issues/469
* We do not wish to mix callbacks and async functions. To keep our code
* testable with jest, let's create our own cancellable wrapper around the
* callback-based setTimeout.
*/

export class AbortError extends Error {
constructor(message = "The operation was aborted") {
super(message);
this.name = "AbortError";
}
}

export const createSleep = () => {
let timeoutId: NodeJS.Timeout | undefined;
let abortFunction: (() => void) | undefined;

const sleep = (delay: number): Promise<void> => {
return new Promise((resolve, reject) => {
abortFunction = () => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
reject(new AbortError());
};

timeoutId = setTimeout(() => {
timeoutId = undefined;
resolve();
abortFunction = undefined;
}, delay);
});
};

const abort = () => {
if (abortFunction !== undefined) {
abortFunction();
}
};

return { sleep, abort };
};
37 changes: 37 additions & 0 deletions tests/util/sleep.unit.test.ts
@@ -0,0 +1,37 @@
import { AbortError, createSleep } from "../../src/util/sleep";

describe("createSleep", () => {
jest.useFakeTimers();

test("sleep should resolve after the specified delay", () => {
const { sleep } = createSleep();
const promise = sleep(1_000);
jest.advanceTimersByTime(1_000);
return expect(promise).resolves.toEqual(undefined);
});

test("sleep should reject with AbortError if aborted before the specified delay", () => {
const { sleep, abort } = createSleep();
const promise = sleep(1_000);
abort();
jest.advanceTimersByTime(1_000);
return expect(promise).rejects.toThrow(AbortError);
});

test("abort should have no effect if called after the delay has passed", () => {
const { sleep, abort } = createSleep();
const promise = sleep(1_000);
jest.advanceTimersByTime(1_000);
abort();
return expect(promise).resolves.toBeUndefined();
});

test("abort can be called multiple times", () => {
const { sleep, abort } = createSleep();
const promise = sleep(1_000);
abort();
abort();
jest.advanceTimersByTime(1_000);
return expect(promise).rejects.toThrow(AbortError);
});
});

0 comments on commit 86e1627

Please sign in to comment.