Skip to content

Instantly share code, notes, and snippets.

@dbani-dev
Last active April 6, 2022 02:31
Show Gist options
  • Save dbani-dev/e925337a2fba3be79e07be58e885280d to your computer and use it in GitHub Desktop.
Save dbani-dev/e925337a2fba3be79e07be58e885280d to your computer and use it in GitHub Desktop.
class PollingBase {
poll = async ({ fn, validate, interval, maxAttempts }) => {
try {
let attempts = 0;
const executePoll = async (resolve, reject) => {
try {
const result = await fn();
attempts++;
console.log({ result });
if (validate(result)) {
return resolve(result);
} else if (maxAttempts && attempts === maxAttempts) {
return reject(new Error("polling: exceeded max attempts"));
} else {
this.pollTimeout = setTimeout(
executePoll,
interval,
resolve,
reject
);
console.log(this.pollTimeout);
}
} catch (err) {
throw err;
}
};
return new Promise(executePoll);
} catch (err) {
throw err;
}
};
}
// Error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout
describe("Polling Base", () => {
it("Testing...", async () => {
jest.useFakeTimers();
const fn = jest.fn();
const validate = (value) => (value === "success" ? true : false);
fn.mockResolvedValueOnce("requested")
.mockResolvedValueOnce("requested")
.mockResolvedValueOnce("requested")
.mockResolvedValueOnce("success");
const base = new PollingBase();
const polling = await base.poll({
fn,
validate,
interval: 1000,
maxAttempts: 4,
});
jest.advanceTimersByTime(4000);
expect(fn).toHaveBeenCalledTimes(4);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment