CEC-5182: add car update status to fleet (#466)

This commit is contained in:
Tristan Timblin
2023-10-13 10:09:49 -07:00
committed by GitHub
parent 0f1886463e
commit db0d3dd319
10 changed files with 292 additions and 27 deletions

29
src/utils/polling.js Normal file
View File

@@ -0,0 +1,29 @@
export default class Polling {
constructor(callback = () => Promise.resolve(), duration = 1000) {
this.callback = callback;
this.duration = duration;
this.timeout = undefined;
}
#sleep() {
this.end();
return new Promise((resolve) => {
this.timeout = setTimeout(resolve, this.duration);
});
}
async start(payload) {
this.callback(payload)
.then(() => {
this.#sleep().then(() => this.start(payload));
});
}
end() {
if (!this.timeout) {
return;
}
clearTimeout(this.timeout);
}
}

31
src/utils/polling.test.js Normal file
View File

@@ -0,0 +1,31 @@
import Polling from "./polling";
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
describe("Polling", () => {
beforeEach(() => {
jest.clearAllMocks();
});
it("starts and ends polling", async () => {
const callback = () => Promise.resolve();
const poll = new Polling(callback, 100);
const spy = jest.spyOn(poll, "callback");
poll.start();
await sleep(500);
poll.end();
await sleep(500);
expect(spy).toHaveBeenCalledTimes(5);
});
it("async polling", async () => {
const callback = () => sleep(100);
const poll = new Polling(callback, 100);
const spy = jest.spyOn(poll, "callback");
poll.start();
await sleep(1000);
expect(spy).toHaveBeenCalledTimes(5);
});
});